AleMal
AleMal

Reputation: 2087

Trap mouseup event only if occur after 1 second of mousedown

In my project I need to perform some operations in the mouseup event, but only if there is at least one second later by his mousedown. I tried this:

$('*').on('mousedown', function (e) {
// make sure the event isn't bubbling
if (e.target != this) {
    return;
}
  //some code
}

var delay = 1000;
var timeout = null;
$(window).on('mouseup', function (e) {

    clearTimeout(timeout);
    timeout = setTimeout(function(){
        // do something
    },delay);
});

but in this way the mouseup event is not associated with mousedown carried out, but to himself. How can I make sure that my code is executed only when the user releases the mouse button after is hold at least a second ??

Thanks to all

Upvotes: 0

Views: 1711

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074276

Hook mousedown and record the time when it happens:

var mousedown;
$(document).on("mousedown", function() {
    mousedown = Date.now();
});

Hook mouseup and see if it's been at least a second:

$(document).on("mouseup", function() {
    var elapsed = Date.now() - mousedown;
    mousedown = undefined;
    if (elapsed >= 1000) {
        // A second or more
    }
});

var mousedown;

$(document).on("mousedown", function() {
  mousedown = Date.now();
  snippet.log("Down at " + new Date().toISOString());
});

$(document).on("mouseup", function() {
  var elapsed = Date.now() - mousedown;
  snippet.log("Up at " + new Date().toISOString());
  mousedown = undefined;
  if (elapsed >= 1000) {
    // A second or more
    snippet.log("A second or more (" + elapsed + ")");
  } else {
    snippet.log("Less than a second (" + elapsed + ")");
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

In the above I hooked mousedown on document, but if you had a strong reason for hooking it on every individual element as in your question, you can adjust as necessary.


On really old browsers, Date.now won't exist. You can easily polyfill it:

if (!Date.now) {
    Date.now = function() {
        return +new Date();
    };
}

Upvotes: 2

Related Questions