Viziionary Viziionary - 1 year ago 91
jQuery Question

Is there a better way to handle a "hover" event on touch devices?

Is there a better way to handle a "hover" (this tapped, then effect active until something else is tapped) event on touch devices than using a global event handler to detect when the user taps something else?

For example, this code might work, but it relies on an event listener attached to the document body, so it's questionable performance-wise.

//note a namespace is used on the event to clear it without clearing all event listeners
$('myDiv').on('touchstart.temp', function () {
//do stuff
$('body').not(this).on('touchstart.temp', function () {
//undo stuff


Use the touchenter and touchleave events, which apply to specific elements.

$("myDiv").on("touchenter mouseover", function() {
    // do hover start code
}).on("touchleave mouseleave", function() {
    // do hover end code