I'm building something mainly for use on tablets, where the user can tap an item on the screen and a class is applied to it. This is what I have so far:
The problems:
I've tried a number of things, none of which have worked. The simplest I've tried (unsuccessfully) is this:
var dragging = false;
$(".items").on("touchmove", function(){
dragging = true;
});
$('.items').on("click touchend", function(event){
if (dragging = true){
}
else{
$('.items').removeClass('selected');
$(this).addClass('selected');
}
});
I would argue this is a more safe way of doing it
Setting variable to false
var dragging = false;
Setting var to true ontouchmove (allows you to reuse this code everywhere in your app)
$("body").on("touchmove", function(){
dragging = true;
});
Your button
$("#button").on("touchend", function(){
if (dragging)
return;
// your button action code
});
Resetting variable (important)
$("body").on("touchstart", function(){
dragging = false;
});
You want to use either of the following:
if(dragging == true)
Or, simply:
if(dragging)
You should only use a single =
sign when you are setting a value, whereas two ==
signs should be used when checking a value. Therefore, your code should look like:
$('.items').on("click touchend", function(event){
if(!dragging)
{
$('.items').removeClass('selected');
$(this).addClass('selected');
}
});
Notice how you do not need to check if dragging == true
because you are not running any code in this case. Instead you can simply check if dragging == false
or, !dragging
You can just check if event is cancelable. It's false after touchmove
$('.items').on("click touchend", function(event){
if (event.cancelable){
$('.items').removeClass('selected');
$(this).addClass('selected');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With