Search code examples
javascriptjquerytouch

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


I am hoping that there is a more elegant solution to this issue. Basically, I have a HTML / Javascript app that will be running on a touch screen kiosk. I am trying to prevent the default click behavior if someone is scrolling through a list of buttons by dragging their finger. At first I tried to preventDefault when it detected a swipe event. But then it occurred to me that it isn't really a swipe event so much as a long mousedown. So I wrote the following code:

var downClick;
var startTime;

$(".TPGSW-wrapper").on('mousedown', function () {

    downClick = new Date();
    startTime = downClick.getTime();

});

$(".TPGSW-wrapper").on('mouseup', function () {

    var upClick = new Date();
    var endTime = upClick.getTime();

    if (endTime - startTime < 250) {
        return false;
    } else if (endTime - startTime >= 300) {
        // This is the action that I can't seem to get to work. 
        // I would like it to stop the click event. I also tried mouseup
        this.on('click', function () { preventDefault; });
    }              

});

This correctly measures the time of the mousedown, but then I can't seem to stop the click event from firing. Any thoughts or suggestions? I am using jquery and this for a webkit browser only. Thanks in advance!


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.