Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open link in new window with Jquery

Tags:

jquery

load

I am trying to open a few links in a new window using Jquery rather than _blank so my html remains valid. My code looks like this:

$(document).ready(function() {
    $('a[id="external-url"]').click(function(){
        $(this).attr('target','_blank');
    });
});

This works just fine except when the link is contained within html I have placed on the page using the Jquery load() method. Can anyone explain why and please help with a solution?

like image 774
mtwallet Avatar asked Apr 09 '10 09:04

mtwallet


People also ask

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

Open in a new window To open a link in a new browser window, hold the Shift on then click the link or right-click the link and select Open link in New Window.

How do I open a new window in JavaScript?

You can use JavaScript to launch a new window. The window. open() method, which allows you to open up new browser window without navigating away from the current page. It is useful when you need to display some popup advertisement or the instructions without navigating away from the current window.

How can you open a link in a new browser window in HTML?

You just need an anchor ( <a> ) element with three important attributes: The href attribute set to the URL of the page you want to link to. The target attribute set to _blank , which tells the browser to open the link in a new tab/window, depending on the browser's settings.


1 Answers

Update: If you're reading this in an HTML5+ world the target attribute is no longer deprecated (no longer missing, to be more accurate) as it was in XHTML 1.0 (the original question context). I suggest if you're reading this now, ignore everything below, use the target attribute whether it throws a compliance warning or not, all browsers support it and it never should have been left out...the fact it was added back in a later spec shows removing it was a mistake.


This will work:

$('a#external-url').live('click', function(){
  $(this).attr('target','_blank');
});

However, IDs should be unique, if you're loading more than 1, they need to have a class instead, like this:

<a href="http://google.com" class="exteral-url">Google</a>

And jQuery like this:

$('a.external-url').live('click', function(){
  $(this).attr('target','_blank');
});

The standards compliant way would be:

$('a.external-url').live('click', function(e){
  window.open(this.href);
  e.preventDefault(); //or return false;
});
like image 135
Nick Craver Avatar answered Nov 17 '22 03:11

Nick Craver