Menu Close

How to open a link in new tab using Jquery when user presses CTRL+Click


In this topic, 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'; 

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 reform your code as below:

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

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

Posted in jQuery, Web Technologies

You can also read...