Open External Links in New Tab with jQuery

  • follow us in feedly
Published February 24, 2013 by Brad Knutson
jQuery New Tab

Current web standards and UI (User Interface) best practices are that links on your site going to external sources should be opened in a new tab or window. This is to give the user the option to open the content without losing their progress on your site. The “back” button in the browser is so 1995…

So you could go through all your links and add the target="_blank" snippet to each a tag, but what if you have a links page with dozens of links? There has to be an easier solution. Enter jQuery…

The code

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
       $(this).attr('target','_blank');
   }
});

This snippet will grab all a tags, pull the URL, compare it to the current domain you are on, and

Let’s test it out. Below are a list of links, which by default should open in the current tab.

As you see, the external links do properly open in a new window. If you view the source, there is no target="_blank" code in the a tag.

The following two tabs change content below.
Founder at Inbounderish
Brad Knutson is a Web Developer in the Twin Cities area of Minnesota. He has experience working with WordPress and Drupal, and also has an interest in SEO and Inbound Marketing.

Keep Up-to-Date

Subscribe

Topics

See a complete list of topics discussed in blog posts here.

Check These Out

Get 2 Weeks Free! Sign Up Today! Premium Managed WordPress Hosting Genesis Framework for WordPress SEO is complex. Tools should be simple. Thesis Theme for WordPress:  Options Galore and a Helpful Support Community

2 thoughts on “Open External Links in New Tab with jQuery

    1. Brad Knutson Post author

      Hey Omar,

      WordPress doesn’t like the “$” used in jQuery, so if you replace every instance of $ with “jQuery” it will work just fine.

Share Your Thoughts

Your email address will not be shown.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">