Search code examples
javascriptjquerykeypress

Simulated key press function with key code arguments Jquery


I'm building a function that simulates keypress events and have adopted the approach from the SO post here.

So I wrote this, with the arguments of two key codes and a time when it should trigger.

function keypress_sim(key_code1, key_code2, time){
var key = 0;
var rand_proxy = Math.floor(Math.random() * 2) + 1;
if(rand_proxy == 1){
    key = key_code1
} else {
    key = key_code2
};
var e = $.Event("keypress",{
    keyCode: key
});
var fire = time;
setTimeout($(document).trigger(e), fire);
$("<div></div>").appendTo('body').text(key);
$("<div></div>").appendTo('body').text(fire);
}

keypress_sim(101,105,100,1500);

This does not work as in a) if I put it in an interval, it still only runs once and b) it returns an "unknown identifier" error. I want this function to be used to "test run" some tasks I wrote in Jquery rather than having to do all keypresses myself.

Where is my mistake?


Solution

  • This:

    setTimeout($(document).trigger(e), fire);
    

    Should be this:

    setTimeout(function() { $(document).trigger(e) }, fire);
    

    The former is calling a function and passing the return value into setTimeout as a parameter, the latter is passing setTimeout a function as a parameter.