My Blog: Highlighting External Links

20 January 2017

I want all of my external links to open in a new window, and for users to know that this will happen before they click. I also want this additional functionality to be automatic, so that other web editors don't need to remember to do something in order to make it happen.

To make a hyperlink open in a new window / browser tab, you need to add a target="_blank" attribute to it. We can then style this with a bit of CSS:

a[target="_blank"] {
    padding-right: 14px;
    background-image: url('/Frontend/Images/University/new-window.png');
    background-repeat: no-repeat;
    background-position: right 50%;
}

This is how it looks.

In most web-page editors, adding the target attribute requires some additional input by the editor.. ticking a checkbox, or typing in a value.. Unfortunately, editors may forget, they may be in a hurry, or they are are just plain lazy. We need a way to make this happen automatically.

JQuery to the Rescue (Again)!

What we need is a way to scan a page for all hyperlinks, then test each of them against a set of criteria, to determine whether to add the target attribute. The criteria needs to exclude all internal hyperlinks (including links that cross our own sub-domains and any root links beginning with a forward slash /), and also exclude protocols such as mailto:, tel:, javascript:, etc.

Fortunately, there exists a piece of code (discovered on StackOverflow) that does this:

$.expr[':'].external = function (obj) {
    return !obj.href.match(/^mailto\:/)
           && (obj.hostname != location.hostname)
           && (obj.hostname != 'baileyweb.localhost')
           && (obj.hostname != 'baileyweb.online')
           && (obj.hostname != 'uni.baileyweb.localhost')
           && (obj.hostname != 'uni.baileyweb.online')
           && (obj.hostname != 'unidocs.baileyweb.localhost')
           && (obj.hostname != 'unidocs.baileyweb.online')
           && !obj.href.match(/^tel\:/)
           && !obj.href.match(/^javascript\:/)
           && !obj.href.match(/^$/)
};

$(document).ready(function () {
    // Insert target="_blank" attribute to external hyperlinks:
    $('a:external').attr('target', '_blank');
});

comments powered by Disqus