Quiero que el usuario pueda tocar y mantener presionado un botón, y después de un cierto período de tiempo, se llama a una función.
Por ejemplo, el texto del botón comienza en negro, se vuelve naranja después de 0,2 s de presionar y luego verde después de 0,5 s de presionar. Si es verde, se activa una función, myFunction().
He hecho un comienzo en él, más ayuda sería apreciada. Gracias :)
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>(También tiene un error por alguna razón)
ACTUALIZADO
por no funcionar completamente, edité el código y también cambié la lógica
Se me ocurrió la variable timerValue que aumenta cada 0,1 s cuando se presiona el mouse y cuando ese timerValue llega a 2, el botón cambia de color a naranja y en 5 cambia a rojo y las impresiones también se activan.
y en mouseup , que se llamará después de que el usuario levante el dedo del mouse, timerValue vuelve a 0 y restablece también la clase de botón
el interval es variable, ¿dónde almaceno la función setInterval y al soltar el mouse lo borro?
Incluí también una etiqueta de párrafo donde se muestra el temporizador para entender cómo funciona.
const btn = document.querySelector(".btn") const timer = document.querySelector("p") //can be deleted let timerValue = 0 let interval; const mousePress = () => { interval = setInterval(() => { timerValue++ timer.innerHTML = timerValue //can be deleted if(timerValue === 2) btn.classList.toggle("orange") if(timerValue === 5) { btn.classList.toggle("red") console.log("triggered") } }, 100) } const mouseRelease = () => { clearInterval(interval) timerValue = 0 timer.innerHTML = timerValue //can be deleted btn.className = "btn" } btn.addEventListener("mousedown", mousePress) btn.addEventListener("mouseup", mouseRelease) .btn.orange{ color: orange; } .btn.red{ color: red; } <button class="btn">Click</button> <p></p>mousedown , mouseup , touchstart , touchend dispara solo una vez cuando se presiona la tecla.
Para verificar, si el usuario todavía lo tiene, puede buscar una variable real dentro de una llamada a la función setTimeout() , detener el tiempo de espera al soltar o usar una llamada a la setInterval() que solo se ejecuta cuando se presiona.
Por ejemplo:
let pressed = false; button.addEventListener("mousedown", () => { pressed = true; setTimeout(() => { if (pressed) { ... } }, 200); }); button.addEventListener("mouseup", () => { pressed = false; }); let timer = null; button.addEventListener("mousedown", () => { pressed = true; timer = setTimeout(() => { ... }, 200); }); button.addEventListener("mouseup", () => { clearTimeout(timer) }); Como ya hay una respuesta con setTimeout() , aquí hay otra solución con setInterval() .
let vars = { interval: null, // used to store the interval id start: 0, // changes to Date.now() on every start. // used to avoid myFunction be called more than once per "hold" myFunctionCalled: false }, myFunction = () => console.log("Yes...?"); button.addEventListener("mousedown", (event) => { // avoid start w/ rightclick if (event.which == 1) { vars.start = Date.now(); vars.myFunctionCalled = false; vars.interval = setInterval(() => { let dur = Date.now() - vars.start; if (dur > 1000) { button.style.color = "green"; if (!vars.myFunctionCalled) { vars.myFunctionCalled = true; myFunction(); } } else if (dur > 500) { button.style.color = "orange"; } else if (dur > 100) { button.style.color = "red"; } }, 10); } }); // using window, so the user can move the mouse window.addEventListener("mouseup", (event) => { // checking again for the mouse key, to avoid disabling it on rightlick if (vars.interval && event.which == 1) { // stop the interval and reset the color to default clearInterval(vars.interval); button.style.color = ""; vars.interval = null; } }) <button id="button">Hold me</button>Si lo está haciendo para una pantalla táctil , necesita usar TouchEvents:
ontouchstart -> when a target is being pressed by a finger ontouchmove -> the active finger moves off the target ontouchcancel -> when the the target has lost focus of a touch event ontouchend -> lifting the finger off of the targetMouseEvents están reservados para dispositivos controlados por mouse/trackpad, como computadoras.
Los TouchEvents están reservados para dispositivos con pantalla táctil, como tabletas y teléfonos.
Lea también esta respuesta para el código.