dimanche 12 juin 2016

jQuery: how to detect and process click, doubleclick and press&hold down for same element?

I have an DIV called "clicker" and I wanted to process 3 events for this element: click, double click and press & hold down or long press. I have been able to gather here and there some useful code that works almost OK on touch device but it seems that single click and press & hold events fired one after other, because when I press down on DIV and hold I got result at first reserved for single click and then is fired events for press & hold. I added also jQuery.mobile beside jQuery 1.12.2 in order to get working but not good as I expected.

<style>
#clicker {
width: 150px;
height: 150px;
margin: 10px;
background: green;
color: #fff;
font-weight:bolder;
font-size: 21px;
}
</styles>

jQ code is here:

$(document).ready(function($){
function single_tap(){
    $("#clicker").html("single tap")
}
//
function double_tap(){
    $("#clicker").html("double tap")
}
//
tapped=false
$("#clicker").on("touchstart",function(e){
    if(!tapped){
      tapped=setTimeout(function(){
          single_tap()
          tapped=null
      },300); //wait 300ms
    }
    else {
      clearTimeout(tapped);
      tapped=null
      double_tap()
    }
    e.preventDefault()
    });
}); 
//----
//process press and hold down on #clicker:
$(document).ready(function($){
  $("#clicker").on("taphold",function(){
        clearTimeout(tapped);
        tapped=null
        $("#clicker").html("pressed and hold me");
  });    
   e.preventDefault()
});

and I tried some combination but nothing helped. Any suggestion? Thank you.

Aucun commentaire:

Enregistrer un commentaire