The browser that handles the mouseover event for touch devices triggers an invalid click event

I have a problem with how browsers handle mouseover and mouseleave events on touch devices.

I have one element A that shows and hides another element B on hover. Element B is a button with a click event. This is great if you use a mouse, but there is no cursor when using touch input. Browsers automatically handle this so that when you click once on an element, the mouseover event is triggered, and when you click elsewhere on the screen, the mouseleave event occurs (which makes sense most of the time).

Now my problem is that both events are fired immediately with one click. And I can’t find a way around this. There seems to be no way to determine if the input was with a mouse or touch input.

I put together a simple jsfiddle demonstrating the problem: https://jsfiddle.net/djmpx1q4/1/

$("#outer").hover(function(){ show(); }, function(){ hide(); }); function show() { $("#inner").css('display', 'block'); $("#inner").on('click', function(){ alert('hello'); }); } function hide() { $("#inner").css('display', 'none'); $("#inner").off('click'); } 
 #outer { padding:50px; width:200px; height: 200px; background-color: #FFFFFF; } #border { border: 1px solid black; width:100%; height:100%; } #inner { display: none; width:100%; height:100%; background-color: #CC0000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="outer"> <div id="border"> <div id="inner"> </div> </div> </div> 

I need this to be 2 taps, first to show the red box and second to fire the click event, while preserving mouse behavior for mouse users.

I'm really not sure what exactly is going on there. The item is not displayed and does not have an event-bound moment when the user picks it up for the first time, and the event is still happening.

+1
source share
1 answer

Try adding the following code to your code:

 function detectMobile() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false;; } } 

This method will try to trigger a touch event. You can then use it to determine if the user is using a touch screen device and adjusts your code accordingly.

See JSFiddle for a (somewhat mutable) example.

0
source

All Articles