Open all links in new tabs with jQuery

technopeasant picture technopeasant · Jun 9, 2011 · Viewed 11.7k times · Source

I have some links that are placed in my page dynamically via JSON and have no way to directly edit them. I want to force all links to open in new tabs, ala target="_blank"

Thought this would work.. but sadly it isn't. Any ideas?

 $('a').attr("target","_blank");

Here's a jsFiddle with the dynamic code: http://jsfiddle.net/danielredwood/mrgta/7/

Answer

Petah picture Petah · Jun 9, 2011

You could do this (which lets the users browser decide whether to open a new window or tab)

$('a').live('click', function() {
    window.open($(this).attr('href'));
    return false;
});