I recently had the need to detect how long a button is pressed and perform different actions based on that. I found some examples on Stack Overflow, but the ones I looked at showed how to use timeout()
.
I came up with this. There are probably other ways to solve this. While searching, I found an example using IIFE in JavaScript, which I then used for this tiny example.
HTML:
<button id="button">click</button>
JavaScript:
(function(window, document, undefined){
'use strict';
var start;
var end;
var delta;
var button = document.getElementById("button");
button.addEventListener("mousedown", function(){
start = new Date();
});
button.addEventListener("mouseup", function() {
end = new Date();
delta = end - start;
if (delta > 0 && delta < 500) {
alert("less than half second:");
}
if (delta > 1000) {
alert("more than a second:");
}
});
})(window, document);
<div id="button">click</button>
or you can just give most any other element the id of "button" and it should work. Here's an example of a fiddle I made which uses a font-awesome icon which has been given the id "button": jsfiddle.net/f6a1cys9/2 \$\endgroup\$