Javascript Tips: Give Visitors An Option To Open Links in New Window

Do you manually append the target="_blank" attribute to <A HREF..> tags because you prefer that visitors open external hyperlinks in new browser windows and don't leave your website ?

While it's your blog and you have the full right to decide how to display external links to your site visitors, how about giving the site visitors an option to decide if they want to open external links in the current window itself, not in new browser windows.

If they want to see the current page on your website again, they can always press the Back button on the browser toolbar. Plus you are also saved from manually typing that extra target="_blank" attribute in each of hyperlink HTML code.

So essentially, we will put a checkbox on the website that users can select if they wish to open external links in a new browser window. Implementing this new functionality is extremely simple,

Step 1: Add the following Javascript code somewhere inside the HEAD tag of your blog template.
<script type="text/javascript">
// Open Links in New Window ?
function changeHyperLinks(newWindow) {
if(newWindow)
targetWindow ="_blank";
else
targetWindow ="_self";
// Process all hyperlinks
for (var i=0; i if(document.links[i].href.indexOf("javascript")==-1 &&
document.links[i].href.indexOf(window.location.hostname)==-1){
document.links[i].target = targetWindow;
}
}
}
</script>
Step 2: Modify the body tag to add the onload function
<body onload="changeHyperLinks(true)">
Step 3: Add a checkbox which people can tick to open links in new window.
<form>
<input type="checkbox"
onclick="changeHyperLinks(this.checked)" checked>
Open links in new window
</form>
Dynamic Drive has another related script that allows you to open only selected links in new windows that are enclosed in a particular named DIV tag.

Update: Anjanesh makes an interesting observation. Since the target attribute for anchors is not allowed in strict HTML or strict XHTML 1.1, the above javascript code can be a good hack to bypass w3c.org validators.

Update: Why was the target attribute removed from XHTML 1.1?

W3C FAQ: It wasn't. XHTML 1.0 comes in three versions: strict, transitional, and frameset. All three of these were deliberately kept as close as possible to HTML 4.01 as XML would allow. XHTML 1.1 is an updated version of XHTML 1.0 strict, and no version of HTML strict has ever included the target attribute. The other two versions, transitional and frameset, were not updated, because there was nothing to update. If you want to use the target attribute, use XHTML 1.0 transitional.