jqueryanchortargetattr

Open all links in new tabs with jQuery


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/


Solution

  • 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;
    });
    

    For jQuery 1.7+:

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