Opening links in a new window was once quick and easy but since the target="_blank" options on a links have died (if you didn’t knew, I’m very sorry to be the one telling you this) the only way left was the javascript way.
The click event on a link cannot be anymore traced by the onclick parameter on the a tag because all the on* events have died too (I know, it’s a massacre!) so I’ll take this example for basis.
We’ll use JQuery‘s selectors to get the links we want.
All external links
$(document).ready(function() { $("a[href^='http://']").click(function(ev){ ev.preventDefault(); window.open(this.href); }); });
All links from a div with ‘#id_div’ id attribute
$(document).ready(function() { $('div#id_div a').bind('click',function(ev) { ev.preventDefault(); window.open(this.href); } ); });
NOTE: I’m using ev.preventDefault() rather than return false to follow JQuery pattern. Just a good practice.
NOTE: ev is just a variable name I gave. You may change it to suit your needs.
Any more ideas?
That’s how I use it too. This is one of the most usual errors I see people do.
I’m continually amazed how sweet jQuery is to work with. It makes it easy as pie to deal with things like this.
Gabriel Svennerberg
February 9, 2009 at 12:17 pm