touchstart and touchend to simulate hover or mouseup and mousedown

samuk picture samuk · Oct 26, 2012 · Viewed 21.5k times · Source

I need to simulate hover or mouseup/down in iphone menu, there are two examples I have given.

<ul id="main_nav">
    <li><a href="http://google.com">google</a></li>
    <li><a href="http://yahoo.com">yahoo</a></li>
    <li><a href="#">Three</a>
      <ul>
        <li><a href="#">sub One</a></li>
        <li><a href="#">sub Two</a></li>
      </ul>
</li>
<li><a href="#">Four</a></li>
</ul>

//bind the touchstart event to the link element
$('li').live('touchstart touchend', function(e){
    $(this).toggleClass('btn-sign-up-hover');
    //alert('alert');
});

a {
    display:block;
    line-height:30px;

}

li{
    background:#096;
}

.btn-sign-up-hover {
    background: #F3F;
}

This is not working in iphone,

but following is work

//bind the touchstart event to the link element
$('li').live('touchstart', function(e){
    $(this).css('background','red');
    //alert('alert');
});

$('li').live('touchend', function(e){
    $('li').css('background','#096');
    //alert('alert');
});

Issue is I need to use toggleClass.

Fiddle example http://jsfiddle.net/UcyAb/

Answer

Sameera Thilakasiri picture Sameera Thilakasiri · Oct 27, 2012
//bind the touchstart event to the link element
$('li').live('touchstart', function(e){
    $(this).addClass('btn-sign-up-hover');
    //alert('alert');
});

$('li').live('touchend', function(e){
    $('li').removeClass('btn-sign-up-hover');
    //alert('alert');
});

Hope this will work.