Insights on Ruby, Git, jQuery, Cappuccino, WordPress, Debian and OS X. Please subscribe if you find something useful!

jQuery – Open External Links In New Window/Tab

Posted: May 18th, 2009 | Author: Jerod | Filed under: jQuery | Tags: | Comments

The common technique to force links to open a new window or tab is to add a “target” attribute like so:

<a href="http://hulu.com" target="_blank">check it out</a>

This works just fine but is not actually valid markup. Fortunately, we can use jQuery to add the target attribute so it doesn’t muck up the HTML.

$(document).ready(function() {
  $('a[rel="external"]').click(function(){
    $(this).attr('target','_blank');
  });
});

Change that invalid link to look like this instead:

<a href="http://hulu.com" rel="external">check it out</a>

Now the link forces browsers to open a new window/tab and the markup is still valid. Easy cheesy.


blog comments powered by Disqus