SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 92 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

location.href.match(/^http:\/\/[^\/]+/)[0];
var elements = document.getElementsByTagName('a');
for(var i=0;i{
// if the currentDomain is in the href, it'll return a value of 0 or more.
if(elements[i].href.lastIndexOf(currentDomain) >= 0)
{
addListener(elements[i], 'click', openWin);
}
}
}
function openWin(evt)
{
evt = evt||window.event;
window.open(this.href);
if(evt.preventDefault)
{
evt.preventDefault();
}else{
evt.returnValue=false;
}
}
addListener(window, 'load', changeLinksToNewWindow);
This example is broken down into three functions and one attachment of an event handler.
After the window has loaded, the changeLinksToNewWindow() function grabs all the links on
the page. The function then checks to see whether the current domain name, which was
retrieved from the window.location object, can be found at the beginning of each link. If they
don??™t match, attach a click event handler so that when a person clicks the link, it opens up in
a new window.
Event Delegation
Adding event handlers can at times be cumbersome, most especially when there are too many
elements to attach to or when you are continually adding new elements into the DOM that
have to react to events. To get around this, you can use event delegation.
Event delegation relies on an element farther up in the DOM stack to receive the event via
event bubbling (see Figure 2-5). From there, you can use the target property of the event (or
srcElement in IE) to determine what element was the source of the click.


Pages:
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104