Posted almost 4 years ago. Visible to the public.

Manually trigger a delegated DOM event

When you register a delegated event 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 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.

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 for a method that attempts to normalize both approaches.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Henning Koch
Last edit:
over 3 years ago
by Henning Koch
javascript, jquery, children
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more