jQuery tutorial: external links

Blog

This is just the first of many other tutorials to come that will show you how to write short and useful jQuery scripts in order to enhance user experience and make your life easier when developing websites. This jQuery tutorial will teach you how to spot all the external links in your website, assign them a class so to style them differently from the other links and open them up in a new window.

Take a peek at the jQuery script we’re going to develop in this tutorial. All of that will be realized in an unobtrusive and accessible way.

Who is this tutorial for?

This tutorial has been thought for those, especially designers and CSS coders, who are about to dive into the fantastic jQuery world and do not have much programming experience, so do not panic! It’s gonna be a piece of cake.

What are we aiming to?

It is good practice to give a different style to all the external links in your web pages, in order to inform users that those links will lead them to external sites. Usually, designers want those links to open in a new window, so that users do not have to leave the website to visit the linked site.

In the past, I used to manually add to all my external links an “external” class, a target blank attribute and a title saying “Opens in a new window”. This was obviously time-consuming and couldn’t always be done. Let’s say for example that you’ve built a website for a client using a CMS. You cannot ask the client to add all these attributes manually every time he or she inserts a link through the CMS. In all likelihood, you’ll end up having a site where external links are not differentiated at all.

Another problem arose when the XHTML 1.0 Strict DTD came into play. In fact, with this new grammar the attribute target was declared as deprecated and made the HTML code not valid.

Thank God, in 2006, some brilliant heads developed a new JavaScript library called jQuery!

Setting up the jQuery environment

First of all you need to download the jQuery library and reference it in the head of your document. I usually prefer to reference the one that is hosted by Google.

Here is the HTML code you should add in the head of your document:

1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

You should then create your own JavaScript file where you will add all your scripts to. I called mine “utility” and here is the HTML code you need to insert in the head of your document. Make sure you put it after the call to the library otherwise nothing will work:

1
<script type="text/javascript" src="scripts/utility.js"></script>

Within the utility file we’re gonna insert what’s called “The ready function“. This is the first thing you need to learn about jQuery. If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded.

1
2
3
$(document).ready(function() {
	    // put all your jQuery scripts in here.
});

Get your hands dirty with some jQuery

First of all we need to find all the external links. To do that we’re going to insert the following code in the $(document).ready() function:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])");

With the code above we are basically looking for each a element whose href attribute begins with http:// or https:// and that does not contain the site domain (location.hostname) in its URL. In this way we won’t get any of the links with relative paths which are internal links and any of the links with absolute paths that contain the site domain in the URL.

We can then assign the “external” class to these links by adding the following bit of code to the previous one, concatenating them with the “.” symbol:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external");

You can now write some CSS to style the external links differently from the other links of the site. I usually apply a specific icon on them.

If you want the external links to open in a new window and to keep your code valid, just add one more bit:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external")
.attr("target","_blank");

This code will add an attribute target to the link element with value _blank. In this way your code will still be valid while you can make your external links open in a new window. We just need to add a final bit of code in order to make it accessible to visually impaired users that browse the site using screen readers:

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")
.addClass("external")
.attr("target","_blank")
.attr("title","Opens new window");

We’ve basically added a title to the link element in order to advice the user that the specific link will open a new window.

Conclusion

You’ve just created your script to manage external links on your website and open them in a new window without jeopardizing accessibility.

More jQuery tutorials will follow so stay tuned!

Posted on Sunday 24 January 2010 at 11:32

11 commenti all'articolo

  1. Karupu says:

    How can i visible the second slider as a default one?

  2. Chai says:

    Now, if i want to open in overlay i.e. popup window what should be the code.

  3. Wendy says:

    Thanks for that comment, I got bit by the www in the hostname, which won’t match if it’s not set in the link, and no subdomains will match either because of it…

  4. zagi says:

    tnx for tutorial, its great!

  5. Terry says:

    I really like your accordion. Donation in the mail. :)

    One question – what is the “DS Store” file?

    Thanks – Terry

  6. Very simple and well explained.

    I especially like how you mention the benefit of unobtrusive javascript, not only for validating strict XHTML, but for empowering clients using a CMS without the need of complicated tags and site-wide conformity.

  7. Kaan says:

    It works. Thank you.

  8. Paulo says:

    The jQuery you used to find all external links is a good reference! I started using it for a project I’m doing, but caught some imperfections. For example, take the following EXTERNAL link:

    http://www.externaldomain.com/?q=mydomain.com

    Your code treats it as an INTERNAL link since your logic searches for ‘your domain’ anywhere in the href value (since you use the ‘asterisk equals’ operator). To be more robust you would have to find links that start with it by using ‘carrot equals’ operator:

    // needs to be repeated for ‘https://’
    $(“a[href^='http://']:not([href^='http://"+location.hostname+"']));

    The code above works almost 100% of the time, but the domain for many sites includes the ‘www.’ prefix and some don’t. So if a link in your body was: “http://www.mydomain.com/page.html” but the address bar of your browser read: “http://mydomain.com”, then it would not match my jQuery above. So we need to be even more precise:

    // again, needs to be repeated for ‘https://’
    $(“a[href^='http://']:not([href^='http://"+location.hostname+"']:not([href^='http://www."+location.hostname+"']));

    Personally, this is getting a bit too long, so I preferred to use regular expressions:

    // for every link
    $(“a”).each(function () {
    var href = $(this).attr(“href”);

    // remove the ‘www.’ prefix from the href value (if it exists)
    var domain = location.hostname.replace(/^(www.)?/, “”);

    // set up a regular expression that sees if a string starts with http[s]://[www.]mydomain.com
    var re = new RegExp(“^https?:\/\/(www.)?” + domain);

    // guaranteed to be an external link
    if (!re.test(href)) {
    $(this).attr(“target”, “_blank”).attr(“title”, “Opens a new window”);
    }
    });

Leave a comment

Please rate this article and help us plan future posts. Comments are moderated. Do not spam for any reason. Ever!