Posted almost 3 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:

Copy
$element = $('div') Trigger.mouseover($element) Trigger.mouseenter($element) Trigger.mousedown($element) Trigger.mouseup($element) Trigger.mouseout($element) Trigger.mouseleave($element) Trigger.click($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:

Copy
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
Trigger.click(button: 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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Henning Koch
Last edit:
5 months ago
by Henning Koch
Attachments:
trigger.coffee
Keywords:
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