Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  81] [ 2]  / answers: 1 / hits: 20213  / 12 Years ago, sat, january 26, 2013, 12:00:00

I don't know whether it is only Chrome problem (can't check now), however let's try the following piece of code, where we bind two events to some element:



$(div).on({
mousemove: function(e) {
console.log(move);
},
click: function(e) {
console.log(click);
}
});


If we try to click the element, we'll find that for some reason mousemove event fires immediately after click, so in console we have:



>> ...
>> click
>> move


DEMO: http://jsfiddle.net/gKqVt/



Note, that mousedown and mouseup events work by the same scenario.



I saw many questions on SO about the same problem, but none (in my search) gave the straightforward idea what to do in order to fire the click event only.


More From » jquery

 Answers
143

This behavior is odd, and it doesn't seem to occur universally (happens in Chrome/IE for me, but not FFX). I think you haven't gotten a straight answer because there isn't one really.



It's possible that the mouse is moved very slightly by the click action, but that's probably not it. Could just be a browser quirk. These don't even seem to be the same event since stopImmediatePropagation in click doesn't stop mousemove from firing. If you focus the element and hit a keyboard button, it will actually trigger click and only click.



Since this is so quirky, it seems like the only way to deal with it is times. As much of a kludge as this is, I do notice that click happens one millisecond before mousemove, so you could get close by comparing the click timestamp + 2 (or 10):



mousemove: function(e) {
if ($(this).data('lastClick') + 10 < e.timeStamp) {


http://jsfiddle.net/gKqVt/3/



This is very specific, though. You should consider not having behavior that occurs immediately on mousemove since it's so frequent.


[#80605] Friday, January 25, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;