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

2019-01-22 12:59发布

问题:

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 div

$('div').mousedown(function() {

});

回答1:

Just watch both mousedown and mouseup and calculate the difference. Here's an example.

(function() { 

    // how many milliseconds is a long press?
    var longpress = 3000;
    // holds the start time
    var start;

    jQuery( "#pressme" ).on( 'mousedown', function( e ) {
        start = new Date().getTime();
    } );

    jQuery( "#pressme" ).on( 'mouseleave', function( e ) {
        start = 0;
    } );

    jQuery( "#pressme" ).on( 'mouseup', function( e ) {
        if ( new Date().getTime() >= ( start + longpress )  ) {
           alert('long press!');   
        } else {
           alert('short press!');   
        }
    } );

}());


回答2:

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.



回答3:

I know this question is pretty old now, but I was looking for something like this and found that Buley's answer was close to what I needed. I figured I'd post what I've done with it to have it function without the mouse up, sort of like an Android longtouch.

// Set the duration of the long press and declare a couple variables
var longpress = 1000;
var start;
var divMouseDown;                       

// Check for mousedown on the element of choice
$("#element").on('mousedown', function(e){
  // Get the time it was clicked
  start = new Date().getTime();

  // See if mouse is still being held down after the longpress duration
  divMouseDown = setTimeout(function(){
    // What we want to happen when mouse is clicked and held for 1 second
  }, longpress);

  // If the mouse leaves the element or is released before the long touch event, 
  // reset variables and stop the function from triggering          
  $("#element").on('mouseup mouseleave', function(){
    if (divMouseDown) {
      clearTimeout(divMouseDown);
    }
    start = 0;
    e.stopPropagation();
  } );

} );


回答4:

Short-click & Long-click events - short press prevented in long press

//from e-OS menu script
var longpress = 800;
var start;
var timer;

//short press - show e-OS system menu
//long press - show e-OS settings
$( "#e-OS-menu" ).on( 'mousedown', function( e ) {
    start = new Date().getTime();
    timer = setTimeout(function(){ console.log('long press!'); }, longpress)
}).on( 'mouseleave', function( e ) {
    start = 0;
    clearTimeout(timer);
}).on( 'mouseup', function( e ) {
    if ( new Date().getTime() < ( start + longpress )  ) {
       clearTimeout(timer);
       console.log('short press!');   
    }
});


回答5:

You can use the following code (tested in JSFiddle):

$('#foo').mousedown(function(){
   $(this).data('lastPressed', new Date().getTime());
}).mouseup(function(){
    var lastPressed = $(this).data('lastPressed');
    if (lastPressed){
        var duration = new Date().getTime() - lastPressed;
        $(this).data('lastPressed', false);
        if (duration > 2000) {
            alert('Your click lasted more than 2 seconds.');
        } else {
            alert('Your click lasted less than 2 seconds.');
        }
    }
}).mouseout(function(){
    $(this).data('lastPressed', false);
});


回答6:

Upgrading and merging Editor and Kevin B replies you can have a fully functional, multi divs, hold-catcher with:

    // Global delta msec timeout
    var delta = 1500;

    $("#foo").on('mousedown', function(event) {

        var thisElement = $(event.currentTarget);
        var deltaTimer = setTimeout(function(){

            console.log('long press!');
            thisElement.removeData('startTimestamp');
        }, delta);

        thisElement.data('startTimestamp', new Date().getTime());
        thisElement.data('timer', deltaTimer);
    }).on('mouseleave', function(event) {

        var thisElement = $(event.currentTarget);
        clearTimeout(thisElement.data('timer'));

        thisElement.removeData('startTimestamp');
        thisElement.removeData('timer');
    }).on('mouseup', function(event) {

        var thisElement = $(event.currentTarget);
        var startTimestamp = thisElement.data('startTimestamp');
        clearTimeout(thisElement.data('timer'));

        if (startTimestamp !== undefined && !isNaN(parseInt(startTimestamp))) {

            if (new Date().getTime() >= (startTimestamp + delta))
               console.log('long press!');
            else
               console.log('short press!');
        }

        thisElement.removeData('startTimestamp');
        thisElement.removeData('timer');
    });


回答7:

In the two years since this question was asked an awesome plugin called jQuery Finger was invented:

http://ngryman.sh/jquery.finger/

$('div').on('press', function(e) {
    console.log(this, e);
});


回答8:

You can get the timestamp when you detect the click on the div thanks to mousedown. Similarly you can get the timestamp when you detect the click release thanks to mouseup.

You then need to compare these two timestamps, if they are greater than 2 seconds (or 2000milliseconds) then you execute your function.



回答9:

This solution executes the action after the time you set. It also cancels the action if you leave the pressed element with the mouse.

var longpress={
        pressed:false,
        longpressed:false,
        presstime:1000
    };

$('#element').on( 'mousedown' , function( event ) {
        longpress.longpressed=false;
        longpress.pressed=true;
        longpress.timeout=setTimeout(function() {
            longpress.longpressed=true;
            //Long press action here!
        },longpress.presstime);
    }).on( 'mouseup' , function( event ) {
        clearTimeout(longpress.timeout);
        if (!longpress.longpressed && longpress.pressed) {
            longpress.pressed=false;
            //Short press action here!
        }
    }).on('mouseleave', function( event ) {
        clearTimeout(longpress.timeout);
        longpress.pressed=false;
    });


回答10:

Simple. No need for long uneccesary coding.

(function(){
    // how many milliseconds is a long press?
    var offset = 500;

    $(".button").on('mousedown', function(e){
        // holds the start time
        $(this).data('start',new Date().getTime());
        $(this).addClass("selected");
    }).on('mouseup', function(e){
        if (new Date().getTime() >= ($(this).data('start') + offset)){
            //alert('ur click lasted for over 2 secs');
            $(this).addClass("selected");
        }else{
            $(this).removeClass("selected");
        }
    }).on('mouseleave', function(e){
        start = 0;
        //you can add destroy lingering functions on mouse leave
    });

}());

http://jsfiddle.net/donddoug/8D4nJ/