Skip to main content

jQuery Open All Hyperlinks in New Window

By Sam Deering

JavaScript

Share:

Free JavaScript Book!

Write powerful, clean and maintainable JavaScript.

RRP $11.95

JavaScript code snippets to to customise your hyperlinks with CSS using jQuery to make them stand out. Also a tip to open hyperlinks in a new window using jQuery.

Open hyperlinks in new window

//open all hyperlinks in a new window using jQuery
$('a[href^="http://"]')
  .attr("target", "_blank");
  $(this).attr('href', newHref).attr("target", "_blank");

You can even add an image or text to your hyperlink with a little bit of chaining. This example adds [^] to the end of your link text.

Custom style external hyperlinks

//open all hyperlinks in a new window using jQuery
//also append a "^" to every link that is external (contains "http://")
$('a[href^="http://"]')
  .attr({
    target: "_blank", 
    title: "Opens in a new window"
  })
  .append(' [^]');
  

Next, add a little bit of jQuery:

$(document).ready(function() {
    $("a[@rel='external']").addClass("external").
       .click(function() { window.open($(this).href); return false; });
});

This finds all anchor tags with rel=”external” and causes them to open a new window when clicked. The “return false;” prevents the current page from switching to the URL as well. As an added benefit, these links get the CSS class “external” so they can be styled, perhaps with something like:

Add background image to external hyperlinks

//change background image of external hyperlinks
A.external {
  padding-left: 15px;
  background: url(external-link.png) top left no-repeat;
}

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

New books out now!

Learn valuable skills with a practical introduction to Python programming!


Give yourself more options and write higher quality CSS with CSS Optimization Basics.