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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)