Read more

Manually trigger a delegated DOM event

Henning Koch
May 17, 2015Software engineer at makandra GmbH

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.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2015-05-17 21:07)