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

mountainash on 02/20/07


Tagged

class window blank title external rel target


Versions (?)


Who likes this?

2 people have marked this snippet as a favorite

basicmagic
heinz1959


relWindow - New window based on 'rel' attr


Published in: JavaScript 


URL: http://www.sitepoint.com/article/standards-compliant-world/

Based on the linked SitePoint article but with options to limit the container (eg body copy) and set the target. Use '_blank' for a new window for each link. Also adds a class (based on the rel value) for styling. Call the 'relWindow' on window load.


  1. <script>
  2. function relWindow(container, relval, atarget) {
  3. if (!document.getElementById) return;
  4. if (!document.getElementsByTagName) return;
  5. var section = (document.getElementById(container) ? document.getElementById(container) : 'document'); // check if container exists or use the whole document
  6. if ( !section.getElementsByTagName('a') ) return;
  7. var links = section.getElementsByTagName('a');
  8. for (var i = 0; i < links.length; i++) {
  9. var link = links[i];
  10. if (link.getAttribute('href') && link.getAttribute('rel') == relval) {
  11. var re = RegExp(relval, 'gi');
  12. if ( re.test( link.getAttribute('rel') ) ) {
  13. link.className = relval; // add a class with the rel value
  14. link.target = atarget;
  15. if ( !link.getAttribute('title') ) {
  16. link.setAttribute('title', 'link opens in another window');
  17. }
  18. }
  19. }
  20. }
  21. }
  22.  
  23. relWindow('page-holder', 'external', 'outside');
  24. </script>
  25.  
  26. <style>
  27. .external { /* set by JavaScript on links with rel="external" */
  28. padding-right: 12px;
  29. background: url('external.png') right center no-repeat;
  30. }
  31. </style>

Report this snippet 

You need to login to post a comment.