简体   繁体   中英

Click and hold event in vanilla javascript

I'd like to be able to have a function attached to an element which will only run once a click has been held on that element for a given amount of time.

There are several ( 1 , 2 , 3 ) questions relating to handling mouse holds in javascript; but these questions either use jQuery or relate to a more particular use case.

I'd like to implement something more general, and I feel like there ought to be a good answer on stack overflow for this problem.

Here is what I get using window.setTimeout :

  var mouseTimer; var myVar; function mouseDown() { mouseTimer = window.setTimeout(myFunction,500); //set timeout to fire in 2 seconds when the user presses mouse button down } function myFunction(){ myVar = true;} var div = document.getElementById("testBtn"); testBtn.addEventListener("mousedown", mouseDown); document.body.addEventListener("mouseup", removeTimer); function removeTimer(){ if(myVar) console.log("a"); if (mouseTimer) window.clearTimeout(mouseTimer); myVar = false; } 
 <button id="testBtn">Test</button> 

 function handleClickHold(el, timeout, callback) { let startTime; const mouseDown = () => (startTime = Date.now()); const mouseUp = (e) => Date.now() - startTime > timeout && callback(Date.now() - startTime); el.addEventListener("mousedown", mouseDown); el.addEventListener("mouseup", mouseUp); } const timeout = 500 // time in ms const btn = document.querySelector('button'); const callback = (ms) => console.log('Held Button for ' + ms + ' ms') handleClickHold(btn, timeout, callback);
 <button>Click</button>

If you want something more general use, you could use a function like this. Takes an element, a timeout, and a callback, so you can apply it in different situations. You can pass the event to the callback as well.

Here's one way of doing it, though it feels rather verbose:

 const addHoldListener = (element, f, timeout) => { let down = 0; let up = 0; const upListener = () => { up = Date.now(); const diff = up - down; if (diff >= timeout) { f(); } element.removeEventListener('mouseup', upListener); }; const downListener = () => { down = Date.now(); element.addEventListener('mouseup', upListener); }; element.addEventListener('mousedown', downListener); }; addHoldListener( document.querySelector('button'), () => console.log('a'), 500 ) 
 <button>Test</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM