How to detect a long press on a div in Jquery?

前端 未结 12 1412
广开言路
广开言路 2020-12-08 04:44

I would like to execute some function when the user presses for 2 seconds on a div.

Is it possible ?

Here is my code to detect the click on the

12条回答
  •  旧时难觅i
    2020-12-08 05:00

    Add a throttle that only allows the click to happen after 2 seconds of mousedown.

    var timer;
    $('div').on("mousedown",function(){
        timer = setTimeout(function(){
            alert("WORKY");
        },2*1000);
    }).on("mouseup mouseleave",function(){
        clearTimeout(timer);
    });
    

    Edit: I added mouseleave too since if the mouse leaves the element and then triggers mouseup, it won't stop the timer.

提交回复
热议问题