How to bind 'touchstart' and 'click' events but not respond to both?
Solution 1:
Update: Check out the jQuery Pointer Events Polyfill project which allows you to bind to "pointer" events instead of choosing between mouse & touch.
Bind to both, but make a flag so the function only fires once per 100ms or so.
var flag = false;
$thing.bind('touchstart click', function(){
if (!flag) {
flag = true;
setTimeout(function(){ flag = false; }, 100);
// do something
}
return false
});
Solution 2:
This is the fix that I "create" and it take out the GhostClick and implements the FastClick. Try on your own and let us know if it worked for you.
$(document).on('touchstart click', '.myBtn', function(event){
if(event.handled === false) return
event.stopPropagation();
event.preventDefault();
event.handled = true;
// Do your magic here
});
Solution 3:
You could try something like this:
var clickEventType=((document.ontouchstart!==null)?'click':'touchstart');
$("#mylink").bind(clickEventType, myClickHandler);
Solution 4:
Usually this works as well:
$('#buttonId').on('touchstart click', function(e){
e.stopPropagation(); e.preventDefault();
//your code here
});
Solution 5:
Just adding return false;
at the end of the on("click touchstart")
event function can solve this problem.
$(this).on("click touchstart", function() {
// Do things
return false;
});
From the jQuery documentation on .on()
Returning
false
from an event handler will automatically callevent.stopPropagation()
andevent.preventDefault()
. Afalse
value can also be passed for the handler as a shorthand forfunction(){ return false; }
.