patternjavascriptMinor
Detect how long an HTML button is pressed
Viewed 0 times
pressedlongdetectbuttonhowhtml
Problem
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
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:
JavaScript:
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:
clickJavaScript:
(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 1000) {
alert("more than a second:");
}
});
})(window, document);Solution
500 and 1000 should be constants.Where you have them now you need to look through to find them in code when you want to change them. I know this is an example, but they're also meaningless.
500 doesn't tell you why half a second matters, but TIMEOUT tells you what the purpose of the number is. Declare your time values at the top of the function with clear names that denote what they're for.Context
StackExchange Code Review Q#113587, answer score: 4
Revisions (0)
No revisions yet.