Blair Wadman 3 minute read
February 3, 2020

Open a link in a new window using jQuery

There are times when you pay want to force links to open in a new window. It could be to open terms and conditions, adverts or external links. Please note that some believe that you should never force a link to open in a new window as that decision should be left to the user. I will not debate this here, but rather explain how to do it should the need arise.

Specify a URL using attribute selectors

Background - CSS Attribute Selectors

In CSS, attribute selectors allow us to style a particular element with a given attribute. You can also style an element with a given attribute and a given value. This is known as a attribute value selector. For example:

HTML

<a title="hello">a link</a>

CSS

 [title=hello] {
  /*styles */
  }

jQuery attribute equals selectors

This concept of attribute value selectors carries over to jQuery. If we want to force a link to a given URL to open in a new tab, we would use the following:

$(document).ready(function(){

  $('a[href=http://www.google.com]').click(function(){
    window.open(this.href);
    return false;
  });
});

In this example, we are targeting a href attribute with a value of http://www.google.com. This is known as an attribute equals selector. window.open will open a new window with the link that has just been clicked (this.href). return false will prevent normal browser behaviour from occurring. In this case, when you click on a link, normal browser behaviour would be for the link to open in the same window, which is what we are trying to override. So in this example, when a user clicks on any link to http://www.google.com, it will open in a new window. It does not matter where the link is on the website, as long as this jQuery has been loaded on the page. And we do not need to add any additional markup, as jQuery handles it all.

Specify a class

It is common to open links in a new window by targeting a class. In the example below, the link is for terms and conditions and the class is called terms.

html

<a href="/terms" class="terms">Terms and conditions</a>

jQuery

$(document).ready(function(){

  $('a.terms').click(function(){
    window.open(this.href);
    return false;
  });

});

Target _blank alternative

The alternative to using javascript is to use the HTML target attribute. There are a few downsides, including:

Here is an example using the HTML target attribute:

<a href="http://www.google.com/" target="_blank">Visit Google</a>