Open All External Links in New Tabs

August 4th, 2010

Here is a quick bit of jQuery to make all external links have the target=_blank attribute.

<script type="text/javascript">
$(function(){
$("a[href^='http:']").not("[href*=EXAMPLE.com']").attr({ target: "_blank" });
});
</script>

You could also use this same technique to add a small friendly image next to these links  notifying the user they are about to leave the site.

<script type="text/javascript">
$(function(){
$("a[href^='http:']").not("[href*=EXAMPLE.com']").attr({ target: "_blank" }).append(" <img src=\"outLink.jpg\">");
});
</script>

One Response to "Open All External Links in New Tabs"

  1. salman says:

    Thanks . Working Perfectly
    I was using

    jQuery(‘a’).each(function() {
    // Let’s make external links open in a new window.
    var href = jQuery(this).attr(‘href’);

    if (typeof href != ‘undefined’ && href != “” && (href.indexOf(‘http://’) != -1 || href.indexOf(‘https://’) != -1) && href.indexOf(window.location.hostname) == -1) {
    jQuery(this).attr(“target”, “_blank”);
    }

    which after some time started opening all links in new tab.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>