External links and the target attribute

I like external pages to open in a new window. So that my page stays open.
But target attribute is deprecated. If you want to validate the XHTML pages, it would result in errors.
The thought behind it was to allow the user to decide for himself if he want to open a new tab or if he want to go on in the same tab.
Often times users just click on the link without thinking about it.

Sometimes as a web programmer it’s just too convenient to simply add ‘target="_blank"’ to external links. Quick and dirty.
There is a Javascript-solution, though. The page itself is XHTML valid, but the behavior is the same as with the target attribute.

It scans for any link that starts with "http://" – in cake usually an external link (internal links are absolute to the root, like "/pages/xyz").

(function() {
    var className = "external";
    var target = "_blank";
    
    var _onload = window.onload;
    
    window.onload = function() {
        var local = new RegExp("^" + window.location.protocol + "//" + window.location.hostname, i);
        var links = document.links;

        for (var i = 0; i < links.length; i++) {
            var link = links[i];
            if (/^https?:\/\//i.test(link.href) && !local.test(link.href)) {	// Not a local link.
                if (link.className && (link.className == 'internal' || link.className.split(" ")[0] == 'internal')) { // enable "override"
                    continue;
                }
                if (link.className && (link.className == 'external' || link.className.split(" ")[0] == 'external')) { // enable "override"
                    // we do not need to add the class again	
                } else {
                    link.className = className + (link.className ? " " : "") + link.className;
                }
                link.target = target;
                link.title = (link.title ? link.title+ " " : "") + "(opens new window)";	// get a title info as well 
            }
        }
        
        if (_onload) _onload();	// Play nice with others.
    }
})();

Of course you can manually override it by using ‘class="internal"’ for always opening it in the same window or ‘class="external"’ to always open in a new window.

And for all of our jQuery users ;):

$(document).ready(function() {
    $("a[href=^http://], a[href=^https://], a.external").attr("target", "_blank");
    $("a.internal").removeAttr("target");
});

Examples:

<a href="/members">opens in the same window</a>
<a href="http://www.domain.e/some_url">opens in a new window/tab</a>

<a href="http://www.domain.e/some_url" class="internal">opens the same window</a>
<a href="/members" class="external">opens in a new window/tab</a>

1 Comment

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.