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

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

    0 讨论(0)
  • 2020-12-08 05:03

    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/

    0 讨论(0)
  • 2020-12-08 05:08

    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);
    });
    
    0 讨论(0)
  • 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;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="button">press here</div>

    0 讨论(0)
  • 2020-12-08 05:11

    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');
        });
    
    0 讨论(0)
  • 2020-12-08 05:12

    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!');   
        }
    });
    
    0 讨论(0)
提交回复
热议问题