Project Insomnia

Project Insomnia is many things, but in this context it is simply a "braindump" of whatever I happen to be thinking/reading/watching/doing at the moment. Parental guidance suggested.

Wednesday, March 05, 2008

Use a class to control whether links open in new windows (tabs) via JavaScript

This took me most of the day to figure out so I'm noting it here for anyone else who needs it. The object is to be able to set a list of links to open in a new window/tab without having to add target="_blank" to each and every one.

First, we wrap our list of links in a DIV and give it a class name to reference later:

<div class="extLinks">
<ul><li><a href="http://www.project-insomnia.com/">Project Insomnia</a></li>
<li><a href="http://www.mouseplanet.com/">MousePlanet</a></li></ul>
</div>


Of course that list of links could be much longer and adding the target="_blank" attribute to each one would surely be a pain. Having thus classed the list, here is the script to add to our HEAD section (or included script file):

function setExtLinkTargets()
{
for ( var e = 0; e < document.anchors.length; e++ ) {
if ( document.anchors[e].className == "extLinks" ) {
document.anchors[e].target = '_blank';
document.anchors[e].title = document.anchors[e].title + ' (opens in new window)';
}
}
document.divs = document.all ? document.all.tags('div') : document.getElementsByTagName('div');
for ( var f = 0; f < document.divs.length; f++ ) {
if ( document.divs[f].className == "extLinks" ) {
document.divExtLinks = document.all ? document.divs[f].all.tags('a') : document.divs[f].getElementsByTagName('a');
for ( var g = 0; g < document.divExtLinks.length; g++ ) {
document.divExtLinks[g].target = "_blank";
document.divExtLinks[g].title = document.divExtLinks[g].title + ' (opens in new window)';
}
}
}
}


This function has two parts; one that processes DIVs with class "extLinks" and another that processes individual links. Why the second? Because if we already have the overhead of the script running on the page load, we might as well have all of our new-window links controlled in one place. So we can also add class="extLinks" to any individual A element for the same effect.

Finally, we just need to call the script as soon as the page has finished loading. I like to put a general onLoadHandler() function in each of my pages:

function onLoadHandler()
{
// other onLoad stuff
setExtLinkTargets();
}


and call it from the BODY element's onload event:

<body onload="onLoadHandler();">

That's it! Now any list or group of links wrapped in a DIV of class "extLinks", or any individual links of class "extLinks" will open in a new window or tab.

Labels: , , ,

|| Andrew, 5:53 PM || ||

"Project Insomnia" and "project-insomnia.com" ™ & SM; site contents © Andrew Rich except where noted.