tags:

views:

62

answers:

3

Hi. 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?

+1  A: 

Use .live()

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

Your code will bind click event to elements that are available at the page load and not to dynamically created elements. Live will bind events to elements that are dynamically created also.

rahul
+3  A: 
$(function(){
    $('a[id="external-url"]').click(function(){
        window.open(this.href);
        return false;
    });
});

http://snipplr.com/view/4626/jquery-snip--open-link-in-new-window/

Sinan
+5  A: 

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;
});
Nick Craver
@Nick thanks once again!
mtwallet
-1 _blank has been deprecated! Even though you are working around the validation by adding the attribute using script.
James Westgate
@James - I was fixing the issue of the click not binding by the OP. If they want to bypass validation, that's their call, not mine to make, the question is about the javascript not working. As a side note, *normally* I'd agree, but `_blank` being deprecated at all was a mildly retarded mistake on W3C's part. I will bet you $100 that 5 years from now **every** browsers will still support `_blank`.
Nick Craver
I got to admit I was midly surprised when I found out about this myself, but we cant choose which standards to ignore now can we ... tried to chaneg the vote down but its too old *sigh*
James Westgate
@James - Edited, added the standards compliant way, it is a perfectly valid point :)
Nick Craver
Changed to +1 :D
James Westgate