We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

skatan on 09/13/07


Tagged

javascript html


Versions (?)


Who likes this?

7 people have marked this snippet as a favorite

jonhenshaw
basicmagic
SpinZ
markupmark
vali29
cidibee
korzhik


open external links in new window


Published in: JavaScript 


Script takes links that are not on your domain and opens them in a new window. This code allows for XHTML strict validation and meets Accessibility criteria on opening new windows.

  1. function handleExternalLinks() { // function makes sure that external links open in new window
  2. var hostName = window.location.hostname;
  3. var links = document.getElementsByTagName("a");
  4. for(var i = 0; i < links.length; i++) {
  5. if(links[i].href.indexOf(hostName) == -1) {
  6. var curTitle = (links[i].getAttribute("title")) ? links[i].getAttribute("title") + " - ": "";
  7. links[i].setAttribute("target", "_blank");
  8. links[i].setAttribute("title", curTitle + "opens in new window");
  9. }
  10. }
  11. }
  12.  
  13. handleExternalLinks(); // Call the function

Report this snippet 

You need to login to post a comment.