Posted By

skatan on 09/13/07


Tagged

javascript html


Versions (?)

Who likes this?

11 people have marked this snippet as a favorite

jonhenshaw
basicmagic
SpinZ
markupmark
vali29
cidibee
korzhik
justinscheetz
mecha
seanpowell
guo3823538


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  

Comments

RSS Icon Subscribe to comments
Posted By: justinscheetz on January 12, 2009

Just what I needed, thank you!

You need to login to post a comment.