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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@user395881 can you clarify a little more? In the example the event didn't actually happen
I would suggest you take a look at createEvent and dispatchEvent
Right ... Now, it makes sense.. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.