relWindow - New window based on 'rel' attr


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

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.


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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.