Posted By

dubogii on 05/17/11


Tagged

window new links external up pop


Versions (?)

Open External Links In New Window


 / Published in: jQuery
 

URL: http://css-tricks.com/snippets/jquery/open-external-links-in-new-window/

  1. $('a').each(function() {
  2. var a = new RegExp('/' + window.location.host + '/');
  3. if(!a.test(this.href)) {
  4. $(this).click(function(event) {
  5. event.preventDefault();
  6. event.stopPropagation();
  7. window.open(this.href, '_blank');
  8. });
  9. }
  10. });
  11.  
  12. You can do this straight with HTML, but that is invalid markup, this takes care of business without invalid code and unnecessary markup.
  13.  
  14. Or, you can still avoid the validation problems and just append the class target=_blank thing to any links with href attributes starting with http://. The example below only targets links in a #content area. Scoping down like that might be a good idea in case your menus are dynamic and create full URLs.
  15.  
  16. $("#content a[href^='http://']").attr("target","_blank");

Report this snippet  

You need to login to post a comment.