Open external links in a new window using jQuery
The way people have typically opened external links in a new window is to use the attribute target="_blank" in an <a> tag. The problem is that in HTML/XHTML Strict, the target attribute is deprecated.
While you can still use the target attribute if you're using the Transitional DOCTYPE, best practice is to adhere to web standards.
The Problem
<a href="http://monkey.com" title="monkey" target="_blank">monkey</a><a href="http://monkey.com" title="monkey" rel="external">monkey</a>The Solution
$(document).ready(function() {
$('a[href^="http"]').not('[href*="mysite.com"]').attr('target', '_blank');
}What the above translates to is:
- when the page is loaded
- check all the <a> tags that start with http
- and do not contain my url
- add target="_blank"
At first this may seem like a bunch of extra code that's doing the same thing as just specifying the target attribute in the first place. But since jQuery is rendered client-side, while the structure of your document is standards-compliant, you get the desired effect of opening external links a new window. Should someone have JavaScript disabled, your links will behave as normal.
If you do a comparison of a view source of your page and compare that with an Inspect Element with Firebug you'll see the difference.
Choosing a DOCTYPE
A Transitional DOCTYPE may be used when you have a lot of legacy markup that cannot easily be converted to comply with a Strict DOCTYPE. But Strict is what you should be aiming for.
From Roger Johansson's article Transitional vs Strict Markup
Add comment
jsfwd on Twitter
- BIXI debuts bike sharing program in Toronto http://bit.ly/cTruQl 1 day 21 hours ago
- Vote #Toronto to host DrupalCon 2012 North America http://bit.ly/aXgBkJ 3 days 19 hours ago
- Toronto #Drupal meetup tonight 6:30pm @CSI http://bit.ly/cGL63w 4 days 19 hours ago
- Display a Twitter Profile using YQL & jQuery http://bit.ly/ajAfu6 5 days 21 hours ago
- Google Images got a facelift.... size, type & colour filters... pagers gone... wow! 1 week 2 days ago
- Wouldn't that just be Drupal? RT @becircle: I just heard the words I feared I might hear some day "They created a GUI for Drush" #drupal 1 week 3 days ago
- #Raptors acquire Leandro Barbosa... w00t w00t!! 2 weeks 5 days ago
- The NBA is a whole lot less interesting today. 3 weeks 22 hours ago
- Site Aliases, Groups and Remote Capabilities! RT @lwalk: New features in Drush 3 http://bit.ly/aIzmxw #drush #drupal 4 weeks 2 days ago
- Twitter delays the OAuthcalypse another 6 weeks http://countdowntooauth.com 4 weeks 3 days ago