JavaScript
Article
By Sam Deering

jQuery Open All Hyperlinks in New Window

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

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;
}

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.