JQuery.on ("click") runs "mouseover" on a touch device

I encounter unwanted behavior when using jQuery $.on("click", function(){}); on touch devices. This is my code below:

Code:

 $(".team").on("mouseover", teamMouseOver); $(".team").on("mouseout", teamMouseOut); $(".team").on("click", teamThumbClicked); function teamMouseOver(event){ console.log(event.type); } function teamMouseOut(event){ // Do something } function teamThumbClicked(event){ console.log("Clicked!"); } 

Problem:

Using the code above, clicking on the .team element on the touch device calls both listeners at the same time, giving me the following console log:

 mouseover Clicked! 

Question Why mouseover work on a touch device? This is not the behavior that I expect from a device that does not have a mouse. This is mistake? Which event should I use, so that a "mouseover" only fires when it is the actual mouse pointer that enters?

My version of jQuery is 2.2.4.

+3
source share
1 answer

I just ran into the same problem, and this is what I did to solve the problem.

 $('#myEl').on('click', myElClickEvent); $('#myEl').on('mouseenter', myElMouseEnterEvent); function myElClickEvent (event) { $(this).addClass('Clicked'); } function myElMouseEnterEvent() { // Turn off events $('#myEl').off(); // After 100 milliseconds cut on events, notice click event won't trigger setTimeout(function() { // .off() is used to prevent from adding multiple click events if the user hovers multiple elements too quickly. $('#myEl').off().on('click', myElClickEvent); $('#myEl').off().on('mouseenter', myElMouseEnterEvent); }, 100); // Do some mouseenter stuff, whatever the reqs. are. } 

This is what I did and it worked for my use case. Hope this helps someone in the future. The idea is to disable the click event in the mouse input event, and then, after 100 milliseconds, cut the mouse click event again. This will prevent both events from being triggered when touched.

0
source

All Articles