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 and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share

Join the discussion