Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
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, Magento, Shopify as well of many other frameworks. Whether you need responsive design, SEO, speed optimisation or anything else in the world of digital then get in touch. If you would like to work with Nathan, simply drop him an email at [email protected]

It’s good to share

Join the discussion