Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webkit <button onclick> does not fire in certain situations

I noticed that in Webkit the <button> element does not fire the onclick event when the mouse is moved from/to child elements of the button during the click. With other words: when the mousedown and mouseup events do not happen on the same element - even if both are children of the button.

The same happens when clicking/releasing on/out of the pixels of the button text.

To clarify I made a testcase: http://jsfiddle.net/gx9B3/

It works fine in FireFox. Fails in Chrome 15 and QtWebkit 4.7.1

Is there a way around this? I need a solution specifically for Webkit because my project is targeted to this browser only.

Solution

I could solve this problem based on the method suggested by Jan Kuča (the solution I accepted). Some additional tweaks were necessary, especially introducing a timer to avoid double clicks. Have a look at my fully working solution at JSFiddle: http://jsfiddle.net/mwFQq/

like image 447
Udo G Avatar asked Oct 10 '22 14:10

Udo G


1 Answers

You could set up a mousedown listener on document.body (to fix the problem on the whole page). You would check if the mousedown event originated from an HTMLButtonElement (or from any of its child elements) and if it did, you set up a mouseup listener (on the button so it does not have to bubble too much) that will check the target property of the mouseup event. If it is contained in the button and is different from the target of the mousedown event, you fire a click event like this:

var e = document.createEvent('Events');
e.initEvent('click', true, true);
button.dispatchEvent(e);

(Do this only for WebKit-based browsers so that you don't get multiple click events in other browsers. Or you could call the preventDefault method of the mousedown event as it should also prevent firing the click event.)

like image 121
J. K. Avatar answered Oct 13 '22 11:10

J. K.