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

前端 未结 12 1386
广开言路
广开言路 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:27

    We can calculate the time difference when the mouse clicks and leave. We can get the timestamp when you click and release a button or div using mousedown and mouseup

    Here's an example to detect the simple click and 2 seconds long press. Here I have done with a button press. Similarly, you can use div

    $(document).ready(function () {
    
    	var pressTime; // store the press time
    
    	$("#pressHere").on('mouseup', function () {
    
    		var holdTime = 2000; //2 milliseconds for long press
    
    		if (new Date().getTime() >= (pressTime + holdTime))
    			$("#status").text("It's a Long Press...");
    		else
    			$("#status").text("It's a Short Press...");
          
    	}).on('mousedown', function () { // When Button Release
    		
        pressTime = new Date().getTime();
        
    	}).on('mouseleave', function () { 	// When Button Leave
    		
        pressTime = 0;
        
    	});
    
    });
    .input-bar-item {
        display: table-cell;
    }
    .button-item {
    margin: 20px;
        width: 30%;
    }
    .width100 {
      width: 60%;
    }
    
    
    
     

提交回复
热议问题