The first uses the OR (||)
operator. If evt evaluates to false (which it will do if it??™s null, undefined, 0, or false), assign
window.event. The second approach tests whether the preventDefault() method exists. You
call it without the parentheses, which will pass the function if it exists (evaluating to true), or
as undefined if it doesn??™t (thus evaluating to false). You wouldn??™t be able to test for the existence
of a property in this way if the property might actually return a value of 0, false, or null.
In that case, you??™d have to be verbose and see whether the property is undefined using typeof
propertyName == 'undefined'.
Tying It All Together
Let??™s tie all the concepts together into a single example, in which you look through all the links
on the page and have all external links open up in a new window. You determine which links
are external by comparing the current domain against the links on the page. If the domains
don??™t match, it will be considered an external link.
function addListener(element, event, listener) {
if (element.addEventListener){
element.addEventListener(event, listener, false);
} else if (element.attachEvent){
element.attachEvent('on'+event, function(){listener.call(element)});
}
}
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 49
function changeLinksToNewWindow()
{
// grab the url and match up to the first "/" after the "http://"
// grab the first (and only) match
var currentDomain = window.
Pages:
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103