3

I found this way, but with it I can only set one keycode in .which, I want to simulate the keys
ALT+space+x at the same time.

For ALT I can use .altKey = true;

 $(".btn").click(function() {
    var e = jQuery.Event("keypress");
    e.which = 88;       // x code value
    e.altKey = true;     // Alt key pressed
    $("input").trigger(e);
 });

How do I add space keycode?

Mathiasfc
  • 1,627
  • 1
  • 16
  • 24
  • Aside the knot in the finger trying to press that with the left hand and not knowing what the bigger picture is, I assume you have a event listener on that key-combo setup executing some code. So why not just make the call to the target function instead of simulating the combination of keys? – Nope Mar 09 '17 at 15:39
  • See http://stackoverflow.com/questions/17504496/javascript-two-key-pressed-at-the-same-time. This is for _handling_ the key presses. So it would appear an event can only hold one `which` key plus the modifiers (alt, shift etc) at a time. You'd need to pass more than one event to the `input` and handle from there. Or just directly call the method, as @Fran says. – G0dsquad Mar 09 '17 at 15:39
  • Yes, I can simply call the function, but the answer to that question answers questions like the function of minimizing the window also that I will need later (alt + space + n), maybe it is better to edit the question, I will see the link @G0dsquad – Mathiasfc Mar 09 '17 at 15:49

1 Answers1

0

I apologize for my previous answer. I thought about how to handle. Now I modify code to handle and trigger:

You can implement it with two events: keyDown and keyUp like this:

var x,
    alt,
    space;

document.addEventListener('keydown', function (e) {
    e = window.event ? event : e;
    switch (e.keyCode) {
        case 88:
            x = true;
            break;
        case 18:
            alt = true;
            break;
        case 32:
            space = true;
            break;
    }
});

document.addEventListener('keyup', function (e) {
    if (x && alt && space) {
        alert("alt + space + x Pressed!");
    }

    x = alt = space = false;
});

function triggerEvent(eventName, keyCode) {
    var event; // The custom event that will be created

    if (document.createEvent) {
        event = document.createEvent('HTMLEvents');
        event.initEvent(eventName, true, true);
    } else {
        event = document.createEventObject();
        event.eventType = eventName;
    }

    event.eventName = eventName;
    event.keyCode = keyCode || null;

    if (document.createEvent) {
        document.dispatchEvent(event);
    } else {
        document.fireEvent('on' + event.eventType, event);
    }
}

triggerEvent('keydown', 88);
triggerEvent('keydown', 18);
triggerEvent('keydown', 32);
triggerEvent('keyup');

https://jsfiddle.net/m83omwq5/1/

Alex Slipknot
  • 2,439
  • 1
  • 18
  • 26