Can someone show me how to monitor how long the mouse is down, and on mouse up display that time in seconds?
I created a CodePen where you can time how long a <button>
element is held down for. This is the relevant code:
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) / 1000.0;
alert("Button held for " + delta + " seconds." )
});
})(window, document);
You probably don't want to use an alert
in your application, but that is a good starting point. You should be able to insert the delta
value into a DOM element without an issue.