javascriptjquerytouch

Detecting how long a mousedown event lasts then preventing mouseup action if over a certain time


Stackoverflow is now a terrible company and website. I won't tolerate using content we contributed to train AI without explicit permission


Solution

  • Okay, after some tests i was able to get it to work with the following code:

    var longpress = false;
    
    $(".TPGSW-wrapper").on('click', function (e) {
        (longpress) ?  e.preventDefault() : alert("clicked");
    });
    
    var startTime, endTime;
    $(".TPGSW-wrapper").on('mousedown', function () {
        startTime = new Date().getTime();
    });
    
    $(".TPGSW-wrapper").on('mouseup', function () {
        endTime = new Date().getTime();
    
        if (endTime - startTime < 250) {
            longpress = false;
            console.log('< 250');
        } else if (endTime - startTime >= 300) {
            longpress = true;
            console.log('>= 300');
        }
    
    });
    

    DEMO

    the click event will fire if the mouse was held down for less than 250 ms, if it's more than 300 ms it will call e.preventDefault and stop the click event.