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 online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
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)