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

zensir on 08/23/06


Tagged

javascript html newwindow websnatndards


Versions (?)


Who likes this?

5 people have marked this snippet as a favorite

meth
panatlantica
nutella
vali29
pagetoscreen


Setting target=“_blank” to external links and standards


Published in: JavaScript 


URL: http://www.maratz.com/blog/archives/2004/11/29/setting-target_blank-to-external-links/

If you want your pages to be valid XHTML-Strict, but you also wish to open external links in new window, the following snippet is doing just that—sets attribute target=“_blank” to all external links in a document to keep your code valid XHTML-Strict. You’ll just have to change variable yourURL. Don’t enter http://www. part of your domain, otherwise something like http://sample.com/ will be treated like any other external link.

  1. // change your domain name:
  2. var yourURL = "sample.com";
  3. function outLinks() {
  4. var outLink;
  5. if (document.getElementsByTagName('a')) {
  6. for (var i = 0; (outLink = document.getElementsByTagName('a')[i]); i++) {
  7. if (outLink.href.indexOf(yourURL) == -1) {
  8. outLink.setAttribute('target', '_blank');
  9. }
  10. }
  11. }
  12. }
  13. window.onload = function() {
  14. outLinks();
  15. }

Report this snippet 

You need to login to post a comment.