Search code examples
javascriptkeyboardtouchdom-eventskey-bindings

Mouse click simulates keyboard key in JavaScript


I have situation that in application (HTML/XUL) there are key bindings for some function keys (F5, F7 & F9) in order to communicate with some other application.

Now I have to make touch-based interface for same app, without keyboard and advanced touch events. All touch clicks are actually same as mouse clicks and I need to have 3 buttons/links that behave same as F5, F7 & F9 keys.

Don't ask for reasons, all I can say is that I need to keep that key bindings.

Can I assign mouse click on link to act like F-key is pressed?


Solution

  • In Jake's answer is most of solution and based on that I gave the whole answer, because is not so easy on first glance for beginners to modify functionality. This is modified function from this thread:

    function simulateKeyPress(target, options) {
        var event = target.ownerDocument.createEvent('KeyEvents'),
            options = options || {};
    
        // Set your options or || default values
        var opts = {
            type: options.type                  || "keypress",
            bubbles: options.bubbles            || true,
            cancelable: options.cancelable      || true,
            viewArg: options.viewArg            || null,
            ctrlKeyArg: options.ctrlKeyArg      || false,
            altKeyArg: options.altKeyArg        || false,
            shiftKeyArg: options.shiftKeyArg    || false,
            metaKeyArg: options.metaKeyArg      || false,
            keyCodeArg: options.keyCodeArg      || 0,
            charCodeArg: options.charCodeArg    || 0
        }
    
        // Pass in the options
        event.initKeyEvent(
            opts.type,
            opts.bubbles,
            opts.cancelable,
            opts.viewArg,
            opts.ctrlKeyArg,
            opts.altKeyArg,
            opts.shiftKeyArg,
            opts.metaKeyArg,
            opts.keyCodeArg,
            opts.charCodeArg
        );
    
        // Fire the event
        target.dispatchEvent(event);
        event.stopPropagation;
    }
    

    And now we call it on desired element/event for desired key to be pressed. Second argument is object with all options changeable (in my case keyCodeArg: 116 is only needed to be send to simulate F5 key press).

    document.getElementById(element).addEventListener('click', function() {
        simulateKeyPress(this, {keyCodeArg: 116});
    });
    

    Mozilla Developer Network has nice articles about KeyboardEvents and initKeyEvent.