simulate ctrl + click with javascript or jquery (to open a new tab without focus)

11,623

Solution 1

Edit:

The Event object in jQuery has a parameter for ctrlKey, you could assign that as true, on click.

var e = jQuery.Event("click");
e.ctrlKey = true;
$('#id').trigger(e);

Reference: jquery trigger ctrl + click

Solution 2

In pure javascript, you can use the MouseEvent for that:

document.getElementById("todo").dispatchEvent(new MouseEvent("click", {ctrlKey: true}));

To programatically open a new tab you can do that:

const a = document.createElement("a");
a.setAttribute("href", "https://www.google.com/");
a.dispatchEvent(new MouseEvent("click", {ctrlKey: true}));

Solution 3

This is a non-jQuery version to simulate keyboard events. This works in both Chrome (WebKit based) and Firefox (Gecko based):

var keyboardEvent = document.createEvent("KeyboardEvent");
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent";


keyboardEvent[initMethod](
                   "keydown", // event type : keydown, keyup, keypress
                    true, // bubbles
                    true, // cancelable
                    window, // viewArg: should be window
                    false, // ctrlKeyArg
                    false, // altKeyArg
                    false, // shiftKeyArg
                    false, // metaKeyArg
                    40, // keyCodeArg : unsigned long the virtual key code, else 0
                    0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0
);
document.dispatchEvent(keyboardEvent);

Or using jQuery, you can simulate by jQuery's event object:

jQuery.event.trigger({
  type:  'keypress',
  which: character.charCodeAt(0)
});
Share:
11,623
decarte
Author by

decarte

Updated on June 18, 2022

Comments

  • decarte
    decarte almost 2 years

    I am playing with the jquery event object but I am stuck as hell

    I read the API https://api.jquery.com/category/events/event-object/ but it's not really helping here, I am not even sure it's a good lead to do that

    Do you have any suggestion ( the problem is to do the exact ctrl + click on a link). I saw some posts about it but nothing seems to work on the recent browsers

    very simple exemple :

    <span id="toto">toto</span>
    <a href="https://google.fr" id="inANewTab"></a>
    
    // The goal is when I click on #toto, I would like #inANewTab trigger 
    // in a new tab without focus. To do that I was thinking
    // about replicate a ctrl+click event
    
    $('#toto').click(function(){
      ???
    })