Use jQuery to make external links open in a new window

How to add target=”_blank” to all external links? I like the way using jQuery to make external links open in a new window…

How to add target=”_blank” to all external links? I like the way using jQuery to make external links open in a new window…


$(document).ready(function() {
$('a[href^="http://"]')
  .attr("target", "_blank");
});

Or a fancy way:


$(document).ready(function() {
$('a[href^="http://"]')
  .attr({
    target: "_blank", 
    title: "Opens in a new window"
  });
});

Or add an image or text to your hyperlink with a little bit of chaining. This example adds [^] to the end of your link text.


$(document).ready(function() {
$('a[href^="http://"]')
  .attr({
    target: "_blank", 
    title: "Opens in a new window"
  })
  .append(' [^]');
});

Or, only external links will open in a new window or tab, and give it a class name:


$(document).ready(function() {
   $("a[href^=http]").each(function(){
      if(this.href.indexOf(location.hostname) == -1) {
         $(this).attr({
            target: "_blank",
            title: "Opens in a new window"
         });
         $(this).addClass("external");
      }
   })
});

If you would like to use simple javascript code no jQuery, here is the snippet. Add parseLink() to onLoad() then you are done.


<script>
function parseLink(){
  var tagA = document.getElementsByTagName('a');
  re=new RegExp("^(http://"+document.domain+")|(javascript:)","i");
  for(var i=0; i<tagA.length; i++){
    if(!tagA[i].href.match(re)){tagA[i].target='_blank'};
  }
}
</script>

Tagged with:
 

Comments are closed.



Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...