External Popup Links Using jQuery

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

With the deprecation of the target attribute in XHTML Strict, opening links in new windows has become a bit trivial, if not annoying, to standardize. I always look for a consistent, unobtrusive approach that degrades gracefully; and since I use jQuery quite frequently, this is how I usually handle them.

The solution is a small piece of jQuery code in your $(document).ready() section:

$(document).ready( function() {

    $('A[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });

});

Now, add rel=”external” to all of the links that you want to open in a new window:

<a href="http://domain.com/" rel="external">Domain.com</a>

From here on out, users that have JavaScript enabled will receive external pages in new windows, while those without JavaScript will still be directed to the appropriate location.

I use rel=”external” because it’s generally a good practice to limit popup links to external websites only. You could very well use rel=”popup” instead, but I prefer the former for semantics.

If you enjoyed this article, please share it with a friend!

33 Responses to External Popup Links Using jQuery

  1. Martijn van der Ven says:

    Wouldn’t rel="external" be even more semantic? (via http://www.sitepoint.com/article/standards-compliant-world)

  2. Cory LaViska says:

    Martijn: A stylish argument, but I prefer class because it allows you to style external links separately. That is a valid point, however, and according to the W3C, you are correct. I’ll have to ponder that one…

  3. Dennis says:

    I also agree with Martijn. With CSS2, you can style links using the REL attribute (but lowly IE6 won’t render it). Use this selector: a[rel="email"]

  4. eksith says:

    You can still use CSS without using a class for it.

    Your styles are still customizable using selectors :

    a[rel^='external'] { color:#333; }

    And your code is still correct :

    $(document).ready( function() {

    $(“a[@rel=*external]“).click( function() {
    window.open( $(this).attr(‘href’) );
    return false;
    });

    });

    Prolem solved without adding any non-semantic or multiple classes in your HTML.

    Keep the HTML clean while tinkering with the CSS and JS, I always say.

  5. Shir says:

    Anyway to specify the dimensions of the poped-up window?

  6. Paul says:

    Thanks for the tip.

    How could you create a popup window where you can specify the size and get rid of the search bar, etc?

    Having trouble finding info on this.

  7. Paul says:

    That will help, thanks Cory

  8. Cory LaViska says:

    I’ve thought a lot about this, and after using both class=”external_link” and rel=”external” I’ve come to decide that the latter is, indeed, the better of the two. Of course, IE6 doesn’t support the attribute CSS selector, but more and more people are upgrading to IE7 these days. Since this is only a small design issue, I’ve decided not to worry about it. I have updated the article to reflect this decision.

    Martijn, Dennis, and eksith: thanks for your suggestions regarding this.

  9. Strange, this just does not work on Firefox 3 on Linux

  10. Andrew Fox says:

    Another method, which should work better with sites you do not have full control over (such as with CMS-driven sites used by multiple users), is to use jQuery to work out if the beginning of the link includes “http://” and not the domain of the site.

    $(“#main a[href^='http://']“).not(“a[href^='http://bob.org']“).not(“a[href^='http://www.bob.org']“).click(function(){
    window.open(this.href,’external’);
    return false;
    });

  11. @Andrew,

    Do you have a link to a website so I can credit you for that bit of code? I have been trying to work out how to do that and up you pop!

  12. Shawn Dones says:

    Dean Edwards has written a JavaScript library to make Microsoft Internet Explorer behave like a standards-compliant browser. Selectors such as a[rel="external"] will work just fine in MSIE. Creating happy, sexy, and clean code.

  13. stephen says:

    @#5
    for a specific sized window just modify the code to the following:

    window.open( $(this).attr(‘href’),this,’width=300,height=200′ );

  14. Vaycheslav says:

    Thank you. I am use for my site. :)

  15. marah says:

    i dont get it. im trying to put it on my media box in friendster, if you know that website. but it doesnt pop up a new window. please help.

  16. Paul Cripps says:

    Couldnt you do this instead:

    $(document).ready(function() {
    $(‘#content a’).filter(function() {
    // if this link/href is not the same as this site
    if (this.hostname && this.hostname !== location.hostname){
    // open in a new window
    $(this).click(function() {
    //alert(“open in new win: ” + this.hostname);
    window.open(this.href);
    return false;
    });
    }
    })
    });

  17. S.o.G. says:

    People who do this should be banned from designing internet pages. Web browsers all offer modifier keys allowing users to open a link in a new window or a new tab IF THATS WHAT THE Y WANT.

    Doing this in your site sends a very strong message to your users. That message is: “I have no respect for you and I want to annoy you”

  18. S.o.G. says:

    A colleague just pointed out to me that it doesn’t NECESSARILY mean “I have no respect for you and I want to annoy you”, and that it could in fact be very well interpreted as “I’m a re-purposed print designer / marketing droid who still really doesn’t get that whole hypertext thing”

  19. Nice one… I do however have one concern or whatever I should call it…Applying this to my site, makes every link show a popup preview. Even those which are on my own site. How is it possible to exclude a domain in that piece of code you posted ?The opposite of this I can do, hehe that’s easy. It’s just to add a domain name

  20. aarontgrogg says:

    any thoughts on pop-up blockers when using window.open? previously, i have done ‘this.target=”_blank”‘, which i know is deprecated, but i feel like target=”_blank” gets around pop-up blockers, right?
    thanks,
    Atg

  21. JenG says:

    Or, S.o.G., it might mean “my corporate client’s legal department mandates that we make it very clear that you are leaving our site.”

  22. Cory LaViska says:

    @JenG – A prime example. I’m a huge advocate of usability, but let’s face it: there are real world exceptions for everything. I don’t necessarily agree with it, but realistically speaking it’s oftentimes inevitable.

  23. Luis says:

    Is it deprecated for a reason…

    This is just a workaround to make the page validate, so essentially you are tricking the validator, which is just as bad as a non-validating page.

  24. Cory LaViska says:

    @Luis – the HTML target attribute is deprecated, but window.open in JavaScript is not. Furthermore, there is no “tricking” the validator because there’s nothing invalid happening here. We’re simply using JavaScript to control behavior, which is exactly what it’s intended for.

    Although I agree that the average webpage probably shouldn’t control whether or not pages open in new windows, it is often necessary in web-based application development. I am, personally, an advocate for Web Standards, but there is a time and place for everything, and it’s not up to you or me to decide what kind of behavior other people’s applications require.

  25. Ben H says:

    Thank you Cory for this elegant solution. :)

  26. Larry Browning says:

    I was having a conflict issue with a jquery library that uses the REL attribute… and it seems that REL is certainly growing in popularity for use as a selector. If you run into issues, might I suggest the REV attribute as an alternative.
    Here is an explanation of their differences: http://www.utoronto.ca/web/HTMLdocs/NewHTML/a_rev.html

  27. Thanks for a nice implementation. Love the unobtrusiveness.

  28. LuK says:

    Thanks for the snippet above! I use it like this

    $(‘area’).click( function() {
    window.open( $(this).attr(‘href’), ‘Capital FM Webradio’, ‘width=300,height=200′ );
    return false;
    });

    the problem I have is, that all IEs don’t open the link in a new small window like all the others do…it’s a webradio module which should pop up and stay open when the user is exploring content on the site (when he listens to the radio he doesn’t want it to stop when he’s clicking a link to another page…) but it does also not need a full new tab/window so this is why I want to have a little popup…

    if a give the area-tag the following inline javascript it works crossbrowser but I have to replace the href attribute with a # and therefore need a noscript tag, not very beautiful and not unobtusive =/

    onclick=”window.open(‘./includes/webradio.php’,'CapitalFM’,'width=300,height=200′);”

    so what I would like to know is if I’m the only one where this is not working or if this is a common issue (like always with ie)…could this be fixed somehow?

    thx for any answers!

  29. LuK says:

    lol…got it^^…IE doesn’t accept whitespace in the title attribute of the javascript –> Capital FM Webradio doesn’t work, when I only take Webradio it does…what a shitty piece of code is this…how much better would the world be without IE??

    What I’m asking myself is if the whole title attribute via javascript thing could be removed and just give the the page that is loaded into the pop up a normal title attribute, would that be taken as the same value?? Didn’t try it yet, but could maybe work =)…

  30. @LuK: The ‘title’ attribute of the window.open function is not literally the title that appears in the title bar of the window that’s opened (that’s still set in the HTML of the page that’s opened), but rather a unique identifier for that window, so usually this is a lower-case, underscore-instead-of-spaces, simple name rather than anything prettier.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>