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?
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 thetarget
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:
However, IDs should be unique, if you're loading more than 1, they need to have a class instead, like this:
And jQuery like this:
The standards compliant way would be:
http://snipplr.com/view/4626/jquery-snip--open-link-in-new-window/
Use .live()
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.
On the contrary what others believe, the
target
attribute with all its values are not deprecated as per HTML5 specification.You can read it about here: http://dev.w3.org/html5/markup/a.html
So, feel free to use it in HTML5.