JavaScript for Opeing External Links in New Window

In yesterday’s post (Users Prefer Opening External Links in New Window), I mentioned about a JavaScript function for providing automatic option (with no server side scripting) to place a New Window icon () next to the external (off-site) links. With this script, the visitors get the option to either open a link in the same window by clicking on the text link or in a new window by clicking on the new window image.

I am not writing about this script in detail. I hope the script will be readable to those who are looking for it! If you don’t care about this, don’t read any further, please!


//Display NEW WINDOW icon next to external links

function fnOpenExtLinks() {
  if (!document.getElementsByTagName) return false;

  var links = document.getElementsByTagName("a");
  var i = links.length;

  //The loop has to be bottom-to-top as we keep inserting
  //into the anchor array within the loop below
  while (i--) {  

    var lnk = links[i];

    //Get the anchor elements with the 'external' attribute is set.
    //'external' is not an HTML standard attribute.
    //You an as well use the target attribute.
    if (lnk.getAttribute('external')) {  

      //create a span element with the image as the background.
      //You can as well simply insert an IMG element too
      var spn = document.createElement("span");
      spn.setAttribute("style","position:relative; height:30px;
        width:100px; margin:0; padding:0; vertical-align:bottom;
        border:none; float:none; background:transparent
        url( no-repeat bottom right;");

      spn.innerHTML ="   ";

      //Create the anchor element for the new window span/image
      var anchr = document.createElement("a");
      anchr.setAttribute("target", "_blank");
      anchr.setAttribute("title", lnk.title + " [opens in a new window/tab]");
      anchr.setAttribute("href", lnk.href);
      //Set the span element as the inner element of anchor

      //insert a space before the new window icon
      var spc = document.createTextNode(' ');
      lnk.parentNode.insertBefore(spc, lnk.nextSibling);
      lnk.parentNode.insertBefore(anchr, lnk.nextSibling.nextSibling);
      if (lnk.getAttribute('target') == "_blank")

Include this script at the end of the body tag or as the onload event. You can modify the script to your needs. You can add more logic int he script to avoid image links and make this script work only for text links. The New Window image display may have some troubles depending on your browser and the way you have defined Style sheets in your pages.

BTW, I am not using this script in this blog. I have opted for opening external links always in new window.

Hope this helps someone! If you have some questions/doubts, please feel free to send me your doubts.

Be the first to comment

Leave a Reply