Posted By

mindshare on 03/16/11


Tagged

window browser jquery new


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

jillella
AllKnightAccess
Balamir
maidul


Automatically use jQuery to Open External Links in New Window (checking domain first)


 / Published in: JavaScript
 

Automatically use jQuery to Open External Links in New Window (checking domain first).

  1. // open external links in new window (checking domain first)
  2. jQuery("a[href^='http']:not([href*='" + document.domain + "'])").each(function () {
  3. jQuery(this).attr("target", "_blank");
  4. });

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: UnseenRevolution on July 27, 2011

I like to use the following for external links:

$(function() { $('a:not([href=""])').each(function() { if (this.hostname !== location.hostname) { $(this).addClass('externalLink').attr('target', "_blank"); } }); });

It gives me the ability to insure that the links are actually external and also allows me to add a class the the external links for styling. For example adding an external link icon.

Full code can be found at:
jQuery External Links

You need to login to post a comment.