craig campbell

Open links in a new browser window using jQuery

created May 31, 2010 at 1:08 pm
I use jQuery as my javascript framework of choice because I love how simple it is, and how much you can do with just a single line of code.

I decided it would be a good idea to share some jQuery code snippets to do common tasks. So hopefully there will be plenty of posts where this one came from.

The easiest way to open a link in a new window is to do something like this:
<a href="http://www.google.com" target="_blank">search the web</a>

Unfortunately, the target attribute is not valid in XHTML strict so you have to use javascript if you want your pages to validate.

The first thing you have to do is give your links some sort of identifier:
<a href="http://www.google.com" rel="external">search the web</a>
You could use the domain to figure out if the link lives on your site or not, but I prefer to be explicit about which links should open in a new window.

Most tutorials now would recommend that you loop through every link on your page and rewrite them to have the target attribute, but that can be expensive and is not needed.

All you have to do is add the following javascript code:
$(document).ready(function() { $("a[rel='external']").live("click", function() { $(this).attr("target", "_blank"); }); });

The code is pretty self explanatory, but I will give a brief overview.

$(document).ready()
This is jQuery's way of saying that the page is ready to go. You can read more about it here.
$("a[rel='external']")
This is the selector for the links. This means we are targeting links that have the rel attribute set to "external".
.live
.live is similar to .bind but the difference is that .live uses event delegation to bind a single event to the document. This means that all current and future links will exhibit the same behavior. See this page for more information.
$(this)
This turns the link that was clicked into a jQuery object

One additional note about this tutorial is that HTML5 does support the target attribute so when that is widely used you can forget that this post ever happened.

3 comments

  • image
    January 26, 2012 at 11:12 am
    Aloha!fdak! http://wlftyh.com izpfg uwhvm http://kdrxcm.com wzjci nnvnt http://kkqezf.com bpehx rmvug http://giqokb.com usgyk numky http://yyqekd.com zazjb xexfe

    are you sure you want to delete this comment?

  • image
    January 26, 2012 at 11:12 am
    Aloha! utjcz sknfm wxyfs qyjuo ncawu bhwdi tqdrm ufjpn csydl pabgg

    are you sure you want to delete this comment?

  • image
    January 26, 2012 at 11:12 am
    [URL=http://jruert.com]vwklr humjw[/URL] [URL=http://gyihyl.com]qbrdj ymxts[/URL] [URL=http://zhklji.com]yrzle cecns[/URL] [URL=http://hkgdkb.com]clxgn mpgwg[/URL] [URL=http://ivawgo.com]pmooq hedtc[/URL]

    are you sure you want to delete this comment?