open external links in new window


/ Published in: JavaScript
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  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

You need to login to post a comment.