views:

5487

answers:

4

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
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
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
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
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

related questions