HOW TO make external links in an existing web page open in a new window with minimal code changes

This tip by Marko can be a big time-saver if you have been ordered to affix the property target="_blank" to half a zillion links in a website (that the last guy who quit forgot to add) so that they open in a new window & vistors to the website are not distracted away.

All the hard work is accomplished by a small Javascript function that takes the domain name of the web page as input, scans all links that do not belong to that domain name & programmatically assigns "_blank" value to the target property of their anchor tags. This function is called in the window onload method.

A cool spin-off of this by the same author is (what I would like to call) the Link Labeler.

It is good to show non-standard web file formats like .PDF, .DOC, .ZIP etc with icons next to it so that when visitors click on the links they are not startled by a File Download dialog box popping up or some other application linked to the file opening up automatically.

Like in the previous case, a Javascript function activated in the window onload method scans an entire web page for references to hyperlinks with non-standard file extensions, adds a CSS class that will put a related icon next to it & makes it open in a new window when clicked.

I've put up a sample that utilizes both the functions for future reference.

Update(7-Oct-2010): Chris Hope shows how you can implement this functionality using jQuery -

$("a").filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).attr('target', '_blank');
Update(27-Aug-2011): How to match external links but ignore subdomains?

$('a').filter(function() {      
        return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1
      })

Comments