Open External Links as Blank Targets via Unobtrusive JavaScript (Microformat Safe Version)

If you are concerned with using the target attribute when using document type definitions for which the target attribute is not valid, and will thus throw validation errors. Then I have written a microformat safe improved version of the unobtrusive javascript written here, and also found (slightly improved) here.

Here it is:

<script>
function externalLinks(){
   if (!document.getElementsByTagName) return;
   var externalRegExp = /(^|\s)external($|\s)/i;
   var anchors = document.getElementsByTagName("a");
   for (var i=0;i<anchors.length;i++){
      var anchor = anchors[i];
      if(
         anchor.getAttribute("href")
         &&   ( !anchor.getAttribute("target") || anchor.getAttribute("target") == ""
            )
         &&   ( externalRegExp.test(anchor.getAttribute("rel")) )
      )
      anchor.target = "_blank";
   }
   return;
}
</script>

With this function, all you need to do is call the externalLinks() function when the page loads and all of the anchor tags with a href value, without an existing target attribute, and that includes the string "external" somewhere in the rel attribute will be given the target="_blank" attribute+value pair.

© Erik Vold 2007-2010. Contact Erik Vold. Top ^