Clint C.
Clint C.

Reputation: 688

jQuery only run function if mouse NOT held down for a certain time in milliseconds

I want to run a function if a mouse is not held down for a certain number of milliseconds.

Below is just an example of how I would think to attempt the code but don't think this will work. Can anyone help accomplish this? Due to a bug in Android I can not use a 'click' event for this.

var timeheld = 0;
     var holdStart, holdEnd, theElement;

     // show modal on click
     $(document).on('mousedown', '.button', function(e) {

          theElement = $(this);
          timeHeld = 0;
          holdStart = Date.now();

     }).mouseup(function() {

         timeHeld = Date.now() - holdStart;
         if(timeHeld < 200) {
             process_click(theElement);

         }

     });

Upvotes: 0

Views: 57

Answers (1)

PeterKA
PeterKA

Reputation: 24638

I think your concept is generally correct with one exception: if you're delegating the mousedown event - for whatever reason, you want to do the same for the mouseup event too.

    $(document).on('mousedown', '.button', function() {
        $(this).data('start', Date.now());
    }).on('mouseup', '.button', function() {
        var df = Date.now() - $(this).data('start');
        console.log( df );
        df >= 200 || process_click( this );
    });

$(document).on('mousedown', '.button', function() {
    $(this).data('start', Date.now());
}).on('mouseup', '.button', function() {
    var df = Date.now() - $(this).data('start');
    console.log( df );
    df >= 200 || process_click( this );
});
function process_click( elm ) {
    console.log( elm );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<BUTTON class="button">BUTTON 1</BUTTON><br>
<BUTTON class="button">BUTTON 2</BUTTON><br>
<BUTTON class="button">BUTTON 3</BUTTON><br>

Upvotes: 1

Related Questions