I want the user to be able to touch and hold a button, and after a certain period of time, a function is called.
E.g. the button text starts as black, turns orange after 0.2s of pressing, and then green after 0.5s of pressing. If it is green, a function, myFunction(), is triggered.
I have made a start on it, more help would be appreciated. Thanks 🙂
var btn = document.getElementById("pressBtn");
var pressedTime = 0;
var elaspedHoldTime;
btn.onmousedown = function() {
if (pressedTime != 0) {
pressedTime = performance.now();
} else {
elaspedHoldTime = performance.now() - pressedTime;
}
if (elaspedHoldTime > 200) {
btn.style.color = "orange";
}
if (elaspedHoldTime > 1000) {
btn.style.color = "green";
}
};
btn.addEventListener("mouseup", function() {
elaspedHoldTime = performance.now() - pressedTime;
btn.style.color = "black";
if (elaspedHoldTime > 500) {
console.log("Call Function Here");
}
pressedTime = 0;
elaspedHoldTime = 0;
});
<button id="btn">Button Text</button>
(It also has a bug for some reason)
>Solution :
You can use for that mousedown and setTimeout in Javascript
in setTimeout first arguement is what function must be run and second is when it should run,
in Javscript setTimeout 1000 is 1 second
in your case
0.5s = 500
0.2s = 200
I also used
mouseupto back to normal the button styling
const btn = document.querySelector(".btn")
const triggerButton = () => {
setTimeout(() => {
btn.className = 'btn orange'
}, 200)
setTimeout(() => {
btn.className = 'btn red'
console.log("Triggered")
}, 500)
}
btn.addEventListener("mouseup", () => {
btn.className = 'btn'
})
btn.addEventListener("mousedown", triggerButton)
.btn.orange{
background: orange;
}
.btn.red{
background: red;
}
<button class="btn">Click</button>