Add a external icon and link target dynamicly

Apr26
  • Share

Difficulty: ★☆☆☆☆

Setting target=”_blank” is not strict valid (x)html. But you want to open all your external URL’s in another window. And have you seen that nice icon on Wikipedia for all the external hyperlinks, which are created dynamicly?
Well today I wrote a Javascript function which does this functionality for you.

Just implement this Javascript (file) between your tags:

/**
 * Ladysign Standard Javascript
 */
function externalLinks() {
    var host = window.location.host;

    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<=anchors.length; i++) {
        var domain = getDomain(anchors[i]);
        if (domain != undefined && anchors[i].href && host != domain){
           anchors[i].target = "_blank";
           anchors[i].className = "external";
        }
    }
}

function getDomain(url){
    var urlStr = url + "";
    var split_domain = new Array();
    split_domain = urlStr.split("/");
    return split_domain[2];
}

window.onload = externalLinks;

And add a stylesheet class “external” together with a nice icon:

  .external { background: transparent url(_img/external.png) no-repeat scroll right center; padding: 0 13px 0 0; }


Leave a comment