Monday, November 2nd, 2009 | Geek Out, Tips, Web Dev

All outside links open in a new window, with jQuery

Today a client asked if all the links on his site could open in a new window. I solved that problem with jQuery, and here’s how:

<script type="text/javascript" charset="utf-8">
  jQuery(document).ready(function() {
     jQuery("a").filter(function() {
     return this.hostname && this.hostname !== location.hostname;
     }).attr('target', '_blank');
  });
</script>

The reason I use the “jQuery” instead of the “$” is because I don’t know what plugin a user might install that might conflict, so using “jQuery” here sidesteps most problems.

This code looks through the page to see if any links are referencing a domain that is NOT the one you’re currently on. I loaded this in the footer to save on loading time. It’s not a cosmetic fix, so it doesn’t matter if it loads last…most people will wait for the page to load before they begin clicking on links.

Filed Under: Geek Out, Tips, Web Dev

No Comments yet

Leave a Comment