Use jQuery to Open All External Links in a New Window

Posted on March 11, 2008 in Tutorial | 7 Comments »

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.

Share This:
  • NewsVine
  • Technorati
  • Reddit
  • Google
  • StumbleUpon
  • Facebook
  • Digg
  • del.icio.us
  • Ma.gnolia
  • TwitThis

7 Responses

  1. Abrir links externos em nova janela com jQuery » Pinceladas da Web - Reflexões sobre XHTML, CSS, PHP e WebStandardsMay 2, 2008 at 5:00 am

    […] Trevor Davis postou em seu site uma solução para abrir links externos em uma nova janela com jQuery, que […]

  2. qO_opMay 6, 2008 at 1:20 pm

    i love you and jQuery ;) Thanx!

  3. jQuery - external links in new window: … « Random TrapMay 8, 2008 at 3:44 pm

    […] pm on May 8, 2008 | # | Tags: jquery jQuery - external links in new window: http://trevordavis.net/blog/tutorial/use-jquery-to-open-all-external-links-in-a-new-window/ […]

  4. adamJuly 15, 2008 at 4:28 pm

    Thats 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

  5. adamJuly 15, 2008 at 4:31 pm

    Whoops, 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”);
    }

  6. RogerSeptember 25, 2008 at 9:33 pm

    Thanks. 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');
  7. TrevorSeptember 26, 2008 at 1:29 pm

    @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.

Speak Your Mind

* Denotes Required Field

  1. Sick of filling out this form? Register or Log in now.

Who Am I?

Trevor Davis I’m Trevor Davis, a 24 year old Front-End Developer. Basically, I make web sites.

By day, I work for Matrix Group International in Alexandria, VA, and by night, I freelance.

Feel free to get in touch with me about anything.

What Have I Done?

  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In
  • Change We Can Believe In

View All My Work »

Bookmarks

  • Google Search Engine Optimization Starter Guide [PDF]

    Google has released a free 22-page Search Engine Optimization Starter Guide containing plenty of well-written, practical and straightforward advice for webmasters. If you've been looking into SEO for a while it probably won't contain anything new for you, but it's useful as a set of guidelines as to what Google considers to be good optimization practice. (psst, Google, with just a little design work it could have looked so much nicer!)

  • The importance of setting expectations

    To make your customer's experience better, be sure to set their expectations.

  • XML Sitemaps Generator

    Insert your URL and let it generate the XML sitemap for you. Very useful for static websites.

  • Train-ee ExpressionEngine Training

    Learn ExpressionEngine with books, screencasts, classroom training and free tutorials from Train-ee.com

  • web.without.words

    Weekly gallery of popular websites reconstructed by removing all words and images, replacing them with blocks.

View All My Bookmarks »