Dean Loh
Dean Loh

Reputation: 57

Open external links in new tab but exclude certain links

I found the following code from somewhere which suppose to open external links in new tab and it's working fine.

The problem I'm facing now, the "scroll to top" button also opens new tab and loads a blank page. The scroll to top button doesn't have href but has an ID. How can I exclude the element ID in the code?

jQuery(document).ready(function($) {
    $('a').each(function() {
        var a = new RegExp('/' + window.location.host + '/');
        if(!a.test(this.href)) {
            $(this).click(function(event) {
                event.preventDefault();
                event.stopPropagation();
                window.open(this.href, '_blank');
            });
        }
    });
});

Upvotes: 0

Views: 51

Answers (1)

Alireza Fattahi
Alireza Fattahi

Reputation: 45465

You can use not selector ( If the id of link is top_link_id)

$("a:not(#top_link_id)").each...

Or

   $("a").not("top_link_id").each...

Upvotes: 2

Related Questions