/ Published in: JavaScript
Open external links in new window.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function openExternalLink(elementId) { if(!document.getElementById(elementId) && !document.getElementsByTagName) return; var links = document.getElementById(elementId).getElementsByTagName('a'); var localURL = 'http://snipplr.com'; for(i=0; i<links.length; i++){ url = links[i].getAttribute('href'); if(url.indexOf(localURL) == -1 && url.indexOf('http') == 0) { links[i].setAttribute('target','_blank'); } } } Example: <div id="links"> <a href="http://snipplr.com">snipplr</a> <a href="http://www.flickr.com">flickr</a> <a href="/new">New Snippet</a> </div> <script type="text/javascript"> openExternalLink('links'); </script>