Posted almost 4 years ago. Visible to the public. Repeats. Deprecated.

Trigger native mouse events with Javascript

If you don't need IE11 support (e.g. in tests), you can use the MouseEvent constructor instead.

The attached Coffeescript helper will let you create mouse events:

$element = $('div') Trigger.mouseover($element) Trigger.mouseenter($element) Trigger.mousedown($element) Trigger.mouseup($element) Trigger.mouseout($element) Trigger.mouseleave($element)$element)

The dispatched events are real DOM events, which will trigger both native and jQuery handlers.
jQuery's .trigger is simpler, but will only trigger event handlers that were bound by jQuery's .on.

Real user actions trigger multiple events

Many user interactions trigger more than one event. E.g. when the user moves the mouse over a button and "clicks" the mouse, she actually triggers a sequence of events (mouseover, mousedown, focus, mouseup, click).

To help emulate this, the Trigger helper has a couple of additional functions that emit event sequences:

Trigger.clickSequence($element) # triggers mouseover, mousedown, focus, mouseup, click Trigger.hoverSequence($element) # triggers mouseover, mouseenter Trigger.unhoverSequence($element) # triggers mouseout, mouseleave

Passing modifiers

You can also pass options, e.g. to simulate a right button click while the CTRL-key was pressed:

Copy 2, ctrlKey: true)

See MDN's full list of options. Also note that browsers will not execute Javascript for some combinations of modifiers.

This was extracted from Unpoly.

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 1 year ago
by Henning Koch
emulate, synthetic, native, real
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