How to open links in new tab or window using JQuery

How to open links in new tab or window using JQuery

How to open links in a new tab or window using JQuery. In this brief article, I am going to show you how to open external links on your website in a new tab using JQuery. There are situations when you actually need this because you cannot go into HTML tag directly and make the necessary changes, and the alternate way that is available for you is going by JavaScript or jQuery to open the external links in a new window/tab.

Solution

The script is very simple and straight forward, it first checks whether the link starts with “HTTP” and then it also checks whether the link contains any words that are similar to our domain name to ensure that no internal links are getting triggered in a new tab/Window when clicked. This way we’re confident that only the external links are targeted to open in new tab/window.

How to open links in new tab or window using JQuery
How to open links in new tab or window using JQuery

Use the script below and you shall be good to go. Just replace the “zaha.in” with your domain name.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"&gt;</script&gt;
<script&gt;
$(function() {
   $("a[href^='http']:not([href*='zaha.in'])").each(function() {
       $(this).click(function(event) {
             event.preventDefault();
             event.stopPropagation();
             window.open(this.href, '_blank');
        }).addClass('externalLink');
   });
});
</script&gt;

Did you Find it helpful? drop a line and share it forward to help others. Have a nice day.

Advertisements

About Syed Hussaini

I am a business consultant with 15+ Years of extensive expertise in IT Services Management (ITSM), Team Management, Mentorship, Knowledge Management, and Business Operations. My involvement in a corporate environment and freelance projects, my career has thought me how to be more productive, proactive, and independent.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.