Opening External Links with jQuery
A tried and true use of JavaScript is to open external links in a new window (or tab, depending on your preferences). I’ve come across countless scripts written to do this task, and even though some are using jQuery or Prototype, they are not making the most out of the library or framework they are using.
Basically, there are three ways to open an external link in a new window:
- Give the a tag a class of ‘popup’, or something to that effect, iterate through the links and open those with class of ‘popup’ in a new window.
- Set the rel attribute to external, and again, iterate through the links in the document, find the ones that contain this attribute and value pair and open the links in a new window.
- Iterate through all the links in the document, check to see if the href contains the current site’s URL and if it doesn’t, pop it open in a new window.
For this example, I am going to assume my links are marked up like so:
<a href="http://google.com" rel="external">google.com</a>
With jQuery, there’s no need to iterate through each link and test for the rel attribute, and it exists, test for the value external. You can simply use CSS selectors to grab only the links you need without having to loop over them, then simply apply the Click Event Helper directly to those links like so:
$(function(){
$('a[rel=external]').click(function(e){
open(this.href);
e.preventDefault();
});
});
That’s what I like about jQuery - you get in, get what you need and get out. ![]()
Tags: JavaScript, jQuery, tips
June 12th, 2008 at 4:59 am
An Andrew Fox posted a great method here -
http://abeautifulsite.net/notebook.php?article=47
I am using it on my site and it works great
June 12th, 2008 at 11:30 am
Yep, looks like we had similar examples
August 29th, 2008 at 5:50 pm
[...] my post on opening external links with jQuery has proven popular, I thought I would port that same technique to Prototype. Yes, it’s just [...]