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 have something as follows:-

window.location = 'http://web-tricks.co.uk/demo';

It will not open in a new link if you hold CTRL 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('http://web-tricks.co.uk/demo','_blank')
   }
   else {
     window.location = 'http://web-tricks.co.uk/demo';
   }
});

and your link will now open in a new tab as you would find with standard HTML links.

 

It’s good to share

Join the discussion