jQuery open external link in a new window
19/03/09
I’ve been tinkering with jQuery for a while now and I love it. As you’d imaging we’re adhering to web standards and a great little solution for opening external links, rather than using target=”_blank“ we add a rel=external, then with jQuery open the given link in a new window.
A site I’ve been working on recently required all external links work this way, so rather than relying on the end users using the CMS always adding the rel=external I’ve re-written the jQuery.
In a nut shell we check to see it the given href is the same as this site. Makes sense right?
Heres the code:
$(document).ready(function() {
$('#content a').filter(function() {
// if this link/href is not the same as this site
if (this.hostname && this.hostname !== location.hostname){
// open in a new window
$(this).click(function() {
window.open(this.href);
return false;
});
}
})
});
I’m sure it could be simplified a little but it works for our requirements.