Open all links in new tabs with jQuery

I have links that are dynamically allocated on my page via JSON and are not able to directly edit them. I want all links to open on new tabs, ala target="_blank"

I thought it would work ... but, unfortunately, it is not. Any ideas?

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

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

+7
source share
5 answers

You can do this (which allows the user browser to decide whether to open a new window or tab)

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

Your problem may be one of the deadlines.

Keep in mind that when you call something like $('a').attr(...whatever...) , it will act instantly on any and all existing elements on the page. So, if your tweet plugin is asynchronous and takes more than 0 milliseconds, it looks like your code is trying to change the attributes on links that do not yet exist on the page.

That is, you can (A) call the tweet plugin, (B) change all the links on the page, and then (C) the tweet plugin will complete and add a bunch of new links on the page that was received previously missed.

So, what could you try, see if your tweet plugin uses some β€œdone” or other completion callback that you could use to change link tags. Or, like the other answer you proposed, which I also approve of, you should not just try to change the link tags, but instead listen (live) on any link, click on the page and intercept them at this point in time. This way you don't have to worry about the time / completion of the tweet plugin, as you can use event delegation ( live ), which works at any given time. See the answer from Petah for a great example of how to do this.

Good luck

+5
source

This works for me:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> </head> <body> <a href="http://www.google.com">test</a> <br /> <a href="http://www.yahoo.com">test2</a> <script> $('a').attr('target', '_blank'); </script> </body> </html> 
+2
source

Try:

 $('a').attr({ target: "_blank" }); 

Also, instead of a space, try _new. If that doesn't work, why not post the generated HTML or all the javascript code?

0
source

It does not work because <a> is not yet part of your page when $('a').attr("target","_blank"); run $('a').attr("target","_blank"); .

0
source

All Articles