0

In JavaScript, how can I create my own event that I can dispatch to another function. For example, I want to create Enter Key press eventso I may dispatch to another function that accepts Keyboard events.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Salman Virk
  • 12,007
  • 9
  • 36
  • 47

1 Answers1

2

From Is it possible to simulate key press events programmatically?

function simulateKeyPress(character) {
  jQuery.event.trigger({ type : 'keypress', which : character.charCodeAt(0) });
}

$(function() {
  $('body').keypress(function(e) {
    alert(e.which);
  });

  simulateKeyPress("e");
});

DEMO

Community
  • 1
  • 1
Moshe K.
  • 700
  • 1
  • 6
  • 9
  • Very nice !!! It works fine. I am wondering if it is possible not to trigger an event but create an event and send to an function that accepts event. Hence, event would not happen at all. – Salman Virk Jan 28 '11 at 21:01
  • 1
    @user395881 can you clarify a little more? In the example the event didn't actually happen – Moshe K. Jan 28 '11 at 21:02
  • 1
    I would suggest you take a look at [createEvent](https://developer.mozilla.org/en/DOM/document.createEvent) and [dispatchEvent](https://developer.mozilla.org/samples/domref/dispatchEvent.html) – Moshe K. Jan 28 '11 at 21:09
  • Right ... Now, it makes sense.. Thanks – Salman Virk Jan 28 '11 at 21:12