Is it possible to simulate key press events programatically in JavaScript
+1
A:
If you are ok to use jQuery 1.3.1:
function simulateKeyPress(character) {
jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}
$(function() {
$('body').keypress(function(e) {
alert(e.which);
});
simulateKeyPress("e");
});
alex2k8
2009-02-27 20:36:55
HiWhat I meant is: 1. Register a key event (letter e executes some JS)2. From a other method I want to programatically press the letter e)
tan
2009-03-03 20:20:40
A:
You can use dispatchEvent()
:
function simulateClick() {
var evt = document.createEvent("KeyboardEvent");
evt.initKeyEvent ("keypress", true, true, window,
0, 0, 0, 0,
0, "e".charCodeAt(0))
var canceled = !body.dispatchEvent(evt);
if(canceled) {
// A handler called preventDefault
alert("canceled");
} else {
// None of the handlers called preventDefault
alert("not canceled");
}
}
I didn't test this, but it's adapted from the code on dispatchEvent()'s documentation. You'll probably want to read through that, and also the docs for createEvent() and initKeyEvent().
Plutor
2009-05-08 12:44:24
A:
You should be using some JS lib with support for wrapping DOM Event Model. From withing there, you can fire and test your handlers.
skrat
2009-10-19 10:40:20
A:
Referring to alex2k8 solution on Feb 27 '09 at 20:36
I like that solution. But how to pass "RIGHT ARROW" key? I've tried simulateKeyPress(39) but not working
Coisox
2010-10-28 05:34:18