WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

jQuery – How to open a link in a new tab when a user presses CTRL + Click

If you are using jQuery for any reason to open a link, you may notice that if you will run into an issue if you have something along the lines of the code below:


window.location = '/demo';

Okay great, it opens the link but a client of mine reported that the link would not open when you use CTRL + Click or CMD + Click. The above code will not open a link in a new tab if you hold CTRL/CMD and click as a normal hyperlink would behave. Instead it will continue to open within the same page. To get around this, you can amend your code as below:-


jQuery('#foo').bind('click', function(e) {
   e.preventDefault(); 
   if (e.ctrlKey){
     window.open('/demo','_blank')
   }
   else {
     window.location = '/demo';
   }
});

Now, your link will now open in a new tab as you would find with standard HTML links. Happy days right?

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

Join the discussion

Related Posts

Related - Detect Scroll up and Down event with jQuery

jQuery / 2nd January 2024

Detect Scroll up and Down event with jQuery

Read More Related - How To Display An Order Delivery Date And Time At Checkout With WooCommerce

WooCommerce / 1st January 2024

How To Display An Order Delivery Date And Time At Checkout With WooCommerce

Read More