Open external links in new window JavaScript.


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

Open external links in new window.


Copy this code and paste it in your HTML
  1. function openExternalLink(elementId) {
  2. if(!document.getElementById(elementId) && !document.getElementsByTagName) return;
  3. var links = document.getElementById(elementId).getElementsByTagName('a');
  4. var localURL = 'http://snipplr.com';
  5. for(i=0; i<links.length; i++){
  6. url = links[i].getAttribute('href');
  7. if(url.indexOf(localURL) == -1 && url.indexOf('http') == 0) {
  8. links[i].setAttribute('target','_blank');
  9. }
  10. }
  11. }
  12.  
  13. Example:
  14. <div id="links">
  15. <a href="http://snipplr.com">snipplr</a>
  16. <a href="http://www.flickr.com">flickr</a>
  17. <a href="/new">New Snippet</a>
  18. </div>
  19.  
  20. <script type="text/javascript">
  21. openExternalLink('links');
  22. </script>

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.