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 event
so I may dispatch to another function that accepts Keyboard events.
Asked
Active
Viewed 2,796 times
0

BenMorel
- 34,448
- 50
- 182
- 322

Salman Virk
- 12,007
- 9
- 36
- 47
1 Answers
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");
});
-
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
-
1I 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