<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=8211560&amp;blogName=Tech+Tips,+Tricks+%26+Trivia&amp;publishMode=PUBLISH_MODE_BLOGSPOT&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http://mvark.blogspot.com/search&amp;blogLocale=en_IN&amp;v=1&amp;homepageUrl=http://mvark.blogspot.com/&amp;vt=-5147029996388199615" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger Navigation and Search"></iframe> <div></div>

Tech Tips, Tricks & Trivia

by 'Anil' Radhakrishna
A seasoned developer's little discoveries and annotated bookmarks.

Search from over a hundred HOW TO articles, Tips and Tricks


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
      })

Labels: , , ,

« Home | Next »
| Next »
| Next »
| Next »
| Next »
| Next »
| Next »
| Next »
| Next »
| Next »

»

Post a Comment