17 Answers
17

You can use fireEvent on IE 8 or lower, and w3c's dispatchEvent on most other browsers. To create the event you want to fire, you can use either createEvent or createEventObject depending on the browser.

Here is a self-explanatory piece of code (from prototype) that fires an event dataavailable on an element:

This answer is more actual now. One thing to add: if there should be a know-typed event (like TransitionEvent, ClipboardEvent, etc) the appropriate constructor could be called.
– KirilJul 1 '14 at 13:04

What if you want to do multiple different things for the same event (or well, callback function in your case) depending on context? :) It's a good alternative but this feels more like a comment than an answer as the OP wants to know how to programmatically trigger an event as opposed to using a callback :)
– SidOfcJun 23 '17 at 13:26

You are quite right that this should have been a comment rather than an answer. Why? Because, uhm, well, .... it doesn't answer the question that was actually asked. Good call. As to your own question, I'd say this would be a great opportunity for constructors in JavaScript! ;-) But without them, I'd say, send an argument with your function call and let that be used to determine what the function should do.
– Kirby L. WallaceSep 11 '17 at 21:05

to all those who downvoted : why is this wrong ?
– user2808054Nov 12 '15 at 16:29

trigger method is not wrong, but it is a jquery method
– Kamuran SönecekDec 29 '15 at 8:33

2

1. document.getElementByClassName doesn't exist. 2. document.getElementsByClassName exist but returns a list. 3. this only works for a select few native events. 4. The last example triggers a jQuery event where no underlying native event exists.
– Glenn JordeMar 23 '16 at 8:57

Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).