Ian Hoar – Passion for Technology – Geeking Out - Technology, Web, Toys, Games, Design, Entertainment, Gadgets, & Geeking Out

Open external links in a new window in one line of jQuery

jQueryI have been against opening new browser windows because a user can choose to do this on their own. There are several ways they can do this like middle middle clicking or right clicking for a contextual menu. I also wrote about it a few years ago as part of my 12 bad website practices. I’m a little more open to this practice now; I believe the choice to open external links in a new window also depends on your website and your taget audience. I constantly middle click myself, because often when you visit a link embedded in article you fully intend on coming back to the source article after taking a peek. Regardless of whether it’s right or wrong, here is a super easy way to make all external links open in a new window using jQuery.

So lets get on with it

Take a look at the snippet below.

$("a[href^='http:'], a[href^='https:']").not("[href*='"+document.domain+"']").attr('target','_blank');

As you can see can see it’s one single line of code, but lets explain what it does exactly.

First you are selecting any href attribute that starts with http: or https: using the attribute starts with selector ^=. Next we make sure that the domain is not our site domain using the .not method. Inside the not method we check if the href contains our domain using the  attribute contains selector *= and document.domain property. Finally if the domain is not the sites domain then an attribute of target blank is added to the link, which looks like target=”_blank”.

This is a basic snippet that you could easily add to by checking if the link is a PDF, or adding a CSS class for displaying external link or PDF icons.

Some of you may be jumping up and down right now saying but “target=”_blank” is not valid html”. Well this is true and it isn’t. As of HTML 5, target=”_blank” is no longer deprecated since it proved to be a valuable attribute.

If you enjoyed this post, you might also be interesting in my article on Doing JavaScript pop-up windows the right way.

One Comment to “Open external links in a new window in one line of jQuery”

  • henk

    I would like to let the visitor choose to open links in a new window. Lets say I have a comparison site and want a checkbox with the option to open the products in new windows. How would I do that?