Reputation: 764
I am using jquery, but I don't want to use jquery mobile, because it is so large, and I don't think I need it. All I am trying to do is get a touch event. This is what I've got.
$('#menuButton').on('click touchstart', function(){
$('#menu').toggleClass('block')
});
It only kind-of works, but seems to be firing twice a lot on my phone. I think I should check for both touchstart and touchend somehow. This needs to work on all types of devices, hopefully. Thanks!
Upvotes: 0
Views: 199
Reputation: 30015
Behold! The lifecycle of a touch:
Now the lifecycle of a mouse click:
If you are listening for both touchstart and click, the event will fire once on mouse or trackpad computers, and twice on touch devices as you are listening for 2 events in the lifecycle.
If you really want to use click for desktops and touchstart of touch devices (a good idea in many cases), you can do something like this:
var clickEvent = (isMobile)?'touchstart':'click';
$('#menuButton').on(clickEvent, function(){
$('#menu').toggleClass('block')
});
How you go about finding isMobile
is another story.
update : I've written a handy script for detecting mobile, if your interested its npm isMobile
Upvotes: 1