How to open links in new tab or window using JQuery

User Rating: 5 / 5

Star ActiveStar ActiveStar ActiveStar ActiveStar Active
 

How to open links in 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 check 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. 

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"></script>
<script>
$(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>

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

About the Author
Syed Hussaini
Author: Syed HussainiEmail: This email address is being protected from spambots. You need JavaScript enabled to view it.
Brief Bio
A business consultant with 13+ Years of extensive expertise in IT Services Management (ITSM), Incident, Problem & Change Management. Additionally, I hold great knowledge of Web development, eLearning Solutions, Web Analytics and CMS Tools.

Get in Touch

Contact me for work opportunities

Follow Me

facebook color   google plus color linkedin color youtube color twitter color