Manually trigger a delegated DOM event

Posted About 9 years ago. Visible to the public.

When you register a delegated event Show archive.org snapshot using on (or the deprecated delegate / live), it is somewhat hard to manually trigger these events manually, e.g. for testing.

After trying jQuery's trigger Show archive.org snapshot to no avail, I had success by using native Javascript methods to create and dispatch an event. For instance, to trigger a mousedown event:

element = $('...').get(0);
event = new MouseEvent('mousedown', { view: window, cancelable: true, bubbles: true });
element.dispatchEvent(event);

element can be the delegate target or one of its descendants.

Also see the list of event classes on MDN Show archive.org snapshot .

Internet Explorer

Internet Explorer doesn't allow you to instantiate a MouseEvent directly. Instead you need to do this:

var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

See this code Show archive.org snapshot for a method that attempts to normalize both approaches.

Henning Koch
Last edit
Almost 9 years ago
Henning Koch
Keywords
javascript, jquery, children
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-05-17 19:07)