Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 370
technopeasant Avatar asked Jun 09 '11 02:06

technopeasant


People also ask

How to open a link in new tab using jQuery?

If we want to force a link to a given URL to open in a new tab, we would use the following: $(document). ready(function(){ $('a[href=http://www.google.com]').click(function(){ window. open(this.

How do I make a link open in a new tab?

How to Open Hyperlinks in a New Browser Tab or Window. The short answer is: just add a target="_blank" attribute to your links (anchor tags). Now when your visitors click that link, it will open in a new window or tab (depending on which web browser they are using and how they configured that browser).

How do I open a new tab window?

Open a new tab Windows & Linux: Ctrl + t. Mac: ⌘ + t.

How do I close a tab in jquery?

window. top. close(); this will close the current tab for you.


2 Answers

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;
});
like image 154
Petah Avatar answered Oct 27 '22 00:10

Petah


Your problem might be one of timing.

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

That is, you might be (A) calling the tweet plugin, (B) changing all links on the page, and then (C) the tweet plugin completes and injects a bunch of new links on the page that got missed earlier.

So, what you could try, is see if the tweet plugin you are using has some kind of "all-done" or other completion callback, that you could then use to change around the link tags. Or, like another answer suggested, which I also endorse, is to not just try and change the link tags, but to instead listen (live) upon any link clicks on the page, and intercept them at that point in time. This way, you don't need to worry about the timing/completion of the tweet plugin, since you could use event delegation (live) which works at any point in time. See the answer from Petah for a great example of how to do this.

Good luck!

like image 27
Funka Avatar answered Oct 26 '22 23:10

Funka