Search code examples
javascriptjqueryinputkeypressmelonjs

Virtual Keyboard with Jquery


I have a div that operates as a button. Once the button is clicked, I want it to simulate the pressing of a key. Elsewhere on Stackoverflow, people have suggested using jQuery.Event("keydown"); but the suggestions all use a .trigger() bound to the button as opposed to .click. So, my example code looks like this:

var press = jQuery.Event("keydown");
press.which = 69; // # The 'e' key code value
press.keyCode = 69;

$('#btn').click( function() {
    $('#testInput').focus();
    $(this).trigger(press);
    console.info(press);
});

I've set up a dummy example at JSFiddle: http://jsfiddle.net/ruzel/WsAbS/

Eventually, rather than have the keypress fill in a form element, I just want to register the event as a keypress to the document so that a MelonJS game can have it.

UPDATE: It looks like triggering a keypress with anything other than the keyboard is likely to be ignored by the browser for security reasons. For updating a text input, this very nice Jquery plugin will do the trick: http://bililite.com/blog/2011/01/23/improved-sendkeys/

As for anyone who comes here looking for the solution in the MelonJS case, it's best to use MelonJS's me.input object, like so:

$('#btn').mousedown(function() {
    me.input.triggerKeyEvent(me.input.KEY.E, true);
});

$('#btn').mouseup(function() {
    me.input.triggerKeyEvent(me.input.KEY.E, false);
});

Solution

  • I'm not sure why, but even though this is triggering the event correctly, it doesn't fill the input with the character.

    I've modified the code to show that the document is indeed receiving keypress events when we say $(document).trigger(p)

    Try it out: http://jsfiddle.net/WsAbS/3/

    var press = jQuery.Event("keydown");
    press.which = 69; // # Some key code value
    press.keyCode = 69;
    press.target = $('#testInput');
    
    
    $(document).on('keydown', function(event) {
        alert(event.keyCode);
    });
    
    $('#btn').click( function() {
        $(document).trigger(press);
    });
    

    I believe this should be good enough for your end goal of a MelonJS game picking up keypresses.