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/
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 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).
Open a new tab Windows & Linux: Ctrl + t. Mac: ⌘ + t.
window. top. close(); this will close the current tab for you.
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;
});
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With