Mauro74 Mauro74 - 5 months ago 19
jQuery Question

How to simulate hover effect on touch devices?

I have a web page with some css3 animation on hover and I would like to make it work on iPad (and any touch enabled device) when the user touch these elements.

Here's my code:

html:

<div id="headBlock">
<a id="arm"></a>
<div id="head">
<div id="blink"></div>
<div id="lid"></div>
<div id="man"></div>
<a id="man-arm"></a>
</div>
</div>


js:

//arm
$('#arm').hover(function(){
$(this).removeAttr('style').css('bottom','244px');
$(this).addClass('hover_effect');

}, function(){
$(this).removeClass('hover_effect');
});

//man arm
$('#man').hover(function(){
$('#man-arm').removeAttr('style');
$('#man-arm').addClass('hover_effect');

}, function(){
$('#man-arm').removeClass('hover_effect');
});


You can see that when the mouse enter the elements I remove the style then apply a style and add the css class 'hover_effect' and when the mouse leaves I remove the 'hover_effect' class.

How can I achieve the same thing on touch devices? The click event doesn't have the a callback so I cannot remove the 'hover_effect' class after the click happens. I tried mousedown and mouseup but it didn't work. I searched stackoverflow and I found this How do I simulate a hover with a touch in touch enabled browsers? but it didn't have any effect.

Any idea anyone?

Thanks

Mauro

Answer

try this

$('#arm').bind('touchstart', function() {
        $(this).removeAttr('style').css('bottom','244px');
        $(this).addClass('hover_effect');
});

$('#arm').bind('touchend', function() {
        $(this).removeClass('hover_effect');
});

similarly for $('#man').