OK Sushi

Force links open in a new window with jQuery

Posted on Friday November 28, 2008 in Work

Occasionally, you will get a client that requires that all external links on their site open in a new window. In the past I have argued against this, on the grounds that a user should be able to decide for themselves where the link opens, but now I don’t really worry about it.

Using jQuery, forcing external links to open in a new window is easy.

What we do is parse the document for any links pointing outside, and add a click handler to them that makes the new window. Easy? Easy.

$(document).ready(function() { $("a[@href^=http]").click(function(){ //find the links pointing to a URL if(this.href.indexOf(location.hostname) == -1) { //check if they point outside window.open( $(this).attr('href') ); //force open the new window return false; } }); });

My flickr photos