jQuery Open All Hyperlinks in New Window

Sam Deering

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
  .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://")
    target: "_blank", 
    title: "Opens in a new window"
  .append(' [^]');

Next, add a little bit of jQuery:

$(document).ready(function() {
       .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;