JavaScript
Article

jQuery Open All Hyperlinks in New Window

By 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
$('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;
}

  • Pingback: jQuery Open All Hyperlinks in New Window » PHP Script Blog()

  • http://www.php-jquery.ir Alireza

    1. This is false that all external link start with: HTTP
    internal link can start with HTTP too.
    2. Also your code remove link TITLE property.
    it seems better to write:
    $(function(){
    $(“a[href^=’http’]:not([href*=window.location.hostname])”).attr({
    target: “_blank”,
    title: $(this).attr(‘title’)+” – this link will be open in a new window”
    }).append(‘ [^]’);
    });

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.