Themeforest

Open External Links In New Browser Window Using jQuery

Since one of our earlier posts – How To Open Links In a New Browser Window we have had many requests at how this can be automated so that only external links are opened in a new window without having to add class “external” to every link.

This can be done in a couple of ways depending on how your links are structured. As well as giving the code for external links, this tutorial also shows a good example of how to combine and use jQuery selectors to filter:

Method 1 – Links With Complete URLs

If your site uses complete URLs, including the domain name, for all links we can identify the external links by selecting those that do not contain your domain name. For this we use a combination of both the not() and :contains() selectors:

$(document).ready(function($){
    $('a').not(':contains(http://www.designchemical.com)').click(function(){
        this.target = "_blank";
    });
});

The above code will therefore identify any link that does not contain http://www.designchemical.com and open this in a new browser window.

View Demo 1

Method 2 – Only External Links Use Complete URLs

If only external links use complete URLs we can just use contains() selector to identify those links with http or https:

$(document).ready(function($){
    $('a:contains(http)').click(function(){
        this.target = "_blank";
    });
});

View Demo 2

2 Comments

  • I would like the Used Equipment -> “Used Stingers” Custom Link (http://www.truckpaper.com/support/links.asp?id=2135) to open in a new tab. Which I think would be your method 2:

     $(document).ready(function($){
        $('a:contains(http)').click(function(){
            this.target = "_blank";
        });
    }); 

    but where do I put this code? (dcwp_jquery_vertical_mega_menu_widget.php)? or does it belong in one of the javascript files?

    Thank you

    • forgot to mention. I am using V1.3.1 of jquery, and 3.1.3 of Wordpress, RT Theme10

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags