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.
1 Answer
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");
});
4 Comments
Salman Virk
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.
Moshe K.
@user395881 can you clarify a little more? In the example the event didn't actually happen
Moshe K.
I would suggest you take a look at createEvent and dispatchEvent
Salman Virk
Right ... Now, it makes sense.. Thanks