In a recent project at work, I had completed implementing a site, and the client was reviewing it. Their company decided that they wanted all external links to open in a new window. This is not a practice that I really like, and others agree:
Opening up new browser windows is like a vacuum cleaner sales person who starts a visit by emptying an ash tray on the customer's carpet. Don't pollute my screen with any more windows, thanks (particularly since current operating systems have miserable window management). If I want a new window, I will open it myself!
Jakob Nielsen: The Top Ten Web Design Mistakes of 1999
Breaking the back button is never a good thing. But this article is not about that.
Back to the site I was implementing. I was really not interested in adding target="_blank" to every single external link, so I came up with a better solution…
The Solution
The site was already using jQuery for other functions, so I figured that I should just use some of its powerfulness to make my life easier.
With a couple lines of code, I solved my problem:
$(document).ready(function(){
$("a[@href^='http']").attr('target','_blank');
});
Check out the demo to see the results.
Explanation
If you know anything about attribute selectors, that should look familiar to you. Basically, it is saying, apply the attribute target="_blank" to all links that begin with http.
Really easy, really powerful, problem solved. Some may say it almost might be preferable to browse the site with JavaScript disabled so that the external links would just open in the same window. But that debate is for another time.
Categories
Recent Articles
May 2012
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | ||
| 6 | 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 | 31 |
24 Comments
qO_op
05.06.2008i love you and jQuery ;) Thanx!
adam
07.15.2008Thats good, I’m doing the same thing my self, but have extended it to not process links to the same domain, and pdfs:
function initExternalLinks() {var h = window.location.host.toLowerCase();
$("a[@href^='http']:not(a[@href^='http://" + h + "']):not(a[@href^='http://www." + h + "']), a[@href$='.pdf']").attr("target", "_blank");
}
May be a more elegant way of doing it, but it works
adam
07.15.2008Whoops, slight error there - in the “not” filter, need to remove the a tags:
function initExternalLinks() {var h = window.location.host.toLowerCase();
$("a[@href^='http']:not([@href^='http://" + h + "']):not([@href^='http://www." + h + "']), a[@href$='.pdf']").css({outline: 'solid 1px red'}).attr("target", "_blank");
}
Roger
09.25.2008Thanks. This is simpler (and more up to date, the @ symbol is no longer required)
jQuery("a[href^='http:']").not("[href*='mydomain.com']").attr('target','_blank');Trevor
09.26.2008@Roger-
Thanks, that makes sense if you have internal URLs that are absolute. One thing I might change is to have the attribute selector select links that start with http and not http:.
Want to make sure to account for https links.
David
02.09.2009Hi,
I just spent a while trying to work out why this did not work for me - looks like it’s incompatible with jQuery 1.3.1 but works OK with your 1.2.6 code.
Any ideas on what the problem is? How to fix?
Thanks.
David.
Trevor
02.09.2009@David-
Try removing the @ from the selector.
See a Demo
David
02.09.2009Brilliant. I guess it’s easy when you know how? :)
Thanks very much, Trevor. Much appreciated.
David
02.10.2009A heads up for everyone else: I run most of my HTML through HTML Tidy (via http://www.topstyle4.com/) to check for errors and format it. Part of that forces CDATA around embedded JavaScript to make it validate with XHTML. E.g.
That stopped the code working for me.
Trevor
02.10.2009@David-
I would not recommend using embedded JavaScript in production. I would definitely move it to an external script.
Vladimir Graschenko
05.04.2009The following code works if you need apply the “new window” rule for all dynamically added links. Useful for UI Tabs or Ajax load.
$("a[href^='http:']:not([href*='" + window.location.host + "'][target='_blank'])").live('click', function(){$(this).attr('target','_blank');
});
Badger
12.15.2009Thanks Trevor for the snippet and everyone else for input. Great little piece of code.
Chadwick Wood
04.13.2010Just the snippet I was looking for, thanks. I’m making an iPhone-optimized version of a site, and I want all external links to load as normal, instead of internal links which use some ajax stuff to give the “native” iPhone feel. This bit of code is exactly what I need.
Jamie Abbott
04.14.2010One thing that caught me out - if you’re pulling in external content and have no control over sloppy coding - remember that jquery is case sensitive.
Couldn’t figure out why not updating the links, and it is because they were HTTP and not http…. doh.
Jamie
paul
05.25.2010thanks I used Roger’s code and it works perfectly in WordPress.
Jeroen van der Tuin
06.15.2010Hi,
Nice bit of code. Here’s my version that also checks for mailto: links.
$(“a:not([href*=yourdomain.com])”)
.not(”[href^=#]”)
.not(”[href^=mailto]”)
.attr(‘target’, ‘_blank’);
Praveen
06.26.2010Good one. I think, this post describes good about it and a perfect solution too!!!
http://praveenbattula.blogspot.com/2010/06/open-all-anchor-links-in-new-window.html
——-
Wood Windows
07.12.2010Roger’s code is really interactive and now it’s working fine after incorporating on my own wordpress blog.
Alex
07.20.2010This seams to work better for excluding links with the same location as the page.
jQuery(“a[href^=‘http:’]”).each(function(){
if(jQuery(this).attr(“href”).search([removed].host) == -1){
jQuery(this).attr(“target”, “_blank”);
}
});
haxd
11.15.2010I used this:
$(function(){
$(“a[href^=‘http’]”).attr(‘target’,‘_blank’);
});
Which worked well. Note for some reason, the @ given in your example was not recognised by jQuery 1.4.4, as well as the shorthand for $(document).ready().
Jason C.
03.18.2011Where does that bit of code go to make it work? If you already have an existing JS file? I know nothing of jQuery but my site is definitely using it.
haxd
03.18.2011Anywhere outside an existing code block so it is executed before page load
Kenneth Purtell
03.22.2011Dropping the @ did it for me too. I am using jQuery 1.5.
Queboi
03.27.2011wow! you guys are very awesome. but my question is how to link multiple jquery in a single site? will it work in I place all the link in a single sheet?
Too late, comments are closed!
Don’t worry, you can email me or contact me on Twitter.