Published in 00:43 of 08/14/2012 by

Published in 00:43 of 08/14/2012

←Home

Open links which points outside your own site in a new window

If you have a website where users can add content and links and you want all the existing links which points outside your own domain to open in a new window, you can add a target="_blank" automatically to every link on the page using Jquery.

Take care! it can cost a while of processing if your page has a lot of links

Pure Java Script

var links = document.links;

for (var i = 0, linksLength = links.length; i < linksLength; i++) {
   if (links[i].hostname != window.location.hostname) {
       links[i].target = '_blank';
   } 
}

If you're using jQuery

$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');‚Äč
  • Programmatically check if Django South has migrations to run in django · 23:48 of 01/03/2013
  • App news reading (portuguese) in web2py · 20:08 of 09/11/2012
  • Lazy DAL - Attempt 3 - Pbreit in web2py · 14:27 of 08/15/2012

  • comments powered by Disqus Go Top