/ Published in: JavaScript
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
<script> function relWindow(container, relval, atarget) { if (!document.getElementById) return; if (!document.getElementsByTagName) return; var section = (document.getElementById(container) ? document.getElementById(container) : 'document'); // check if container exists or use the whole document if ( !section.getElementsByTagName('a') ) return; var links = section.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var link = links[i]; if (link.getAttribute('href') && link.getAttribute('rel') == relval) { var re = RegExp(relval, 'gi'); if ( re.test( link.getAttribute('rel') ) ) { link.className = relval; // add a class with the rel value link.target = atarget; if ( !link.getAttribute('title') ) { link.setAttribute('title', 'link opens in another window'); } } } } } relWindow('page-holder', 'external', 'outside'); </script> <style> .external { /* set by JavaScript on links with rel="external" */ padding-right: 12px; background: url('external.png') right center no-repeat; } </style>
URL: http://www.sitepoint.com/article/standards-compliant-world/