Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triggering click event with modifier keys on input element

I'm writing a test for some functionality that involves user shift-clicking on a checkbox. I'm using $('input').trigger($.Event('click', { shiftKey: true })); to simulate that.

But when the event listener gets called, event.shiftKey property always gets reported as false when originating from my synthetic events, while real clicks produce the desired effect. What's more confusing, triggering the same event on a non-input element seems to work just fine. See http://jsfiddle.net/huskssk1/ for example.

I'm observing this behaviour both in my browser (Chrome 39, OS X) and test stack (Poltergeist 1.5.1 + PhantomJS 1.9.8).

What's causing this? Is there any way around it?

PS My full test stack is Ruby on Rails + RSpec + Capybara + Poltergeist + PhantomJS, if you know a better way to trigger shift-click, do let me know!

like image 976
Toms Mikoss Avatar asked Jan 09 '23 02:01

Toms Mikoss


1 Answers

@Vijay is correct, it's jQuery issue. The problem is in this line: https://github.com/jquery/jquery/blob/master/src/event.js#L577. It was added in jquery 1.9.0

So, you can monkey-patch jQuery by adding following code to your javascript:

delete jQuery.event.special.click.trigger

and checkbox click will work as expected: http://jsfiddle.net/ofbazqvo/ (note, I commented e.stopPropogation() on body too) with one exception: input.checked value will be invalid in you 'onclick' callback, but will update to correct value later (surprisingly, it's why this special checkbox handling was added to jquery).

Alternatively you can dispatch event manually via plain javascript: http://jsfiddle.net/6dutftkt/1/. This works without any quirks in chrome.

like image 161
glyuck Avatar answered Jan 26 '23 21:01

glyuck