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

前端 未结 12 1393
广开言路
广开言路 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条回答
  •  隐瞒了意图╮
    2020-12-08 05:10

    So this is obviously a long way in the future, but for people who want to do this still, a super simple and pretty elegant way to do this is by combining the clearTimeout function with mouseup / mouseout events:

    $('#button').mousedown(function(){
       var timer = setTimeout(
       	() => {alert('long press occurred');}, 600
       );
    }).mouseup(function(){
        clearTimeout(timer);
    }).mouseout(function(){
        clearTimeout(timer);
    });
    #button {
      width: 50px;
      height: 50px;
      background-color: blue;
      color: white;
      display: flex;
      flex-direction: column;
      text-align: center;
      justify-content: center;
    }
    
    
    press here

提交回复
热议问题