Search code examples
javascriptclickalt

Alt-click an element with Javascript


I know there are ways to detect an alt-click, but I'm curious- is it possible to alt-click an element?

You could call the function that the click event calls, but just say hypothetically we're dealing with some system that dynamically generates the function and places it in the page as it is rendered (or some other wild explanation).


Solution

  • This can be done in vanilla JS using initMouseEvent:

    event.initMouseEvent(type, canBubble, cancelable, view, 
                         detail, screenX, screenY, clientX, clientY, 
                         ctrlKey, altKey, shiftKey, metaKey, 
                         button, relatedTarget);
    

    As you can see, arguments ten through thirteen apply modifier keys to a programmatically triggered mouse event. The MDN page linked above has a small example on how to use initMouseEvent practically:

    function simulateClick() {
        // create a new mouse event
        var evt = document.createEvent("MouseEvents");
    
        // initialize all the parameters of the event
        evt.initMouseEvent("click", true, true, window,
          0, 0, 0, 0, 0,
          false, false, false, false,  // ctrl, alt, shift, meta
          0, null);
    
        var cb = document.getElementById("checkbox");
    
        // actually fire the event on the `cb` element
        var canceled = !cb.dispatchEvent(evt);
    
        // if the event was cancelled...
        if(canceled) {
            //...
        }
    }
    

    Note that older IE versions only support initEvent, which does not seem to allow modifier key options.