+ 11

Press and hold effect in JavaScript

I want to have a press and hold like effect just like triggers in games which keep firing as long as you hold the trigger btn. After some google searches I found this https://code.sololearn.com/WyQOUoJ6DWLj/?ref=app which works fine in my laptop but not in my mobile phone :( Now I could make ripple like effect but that is not what I want.. The problem with that is it uses css keyframes to animate but still the function is called only once... I want to keep calliing the function as long as i hold the btn.

22nd Dec 2020, 4:56 AM
Shreyansh
Shreyansh - avatar
4 Respostas
+ 5
1) don't use anonymous functions as event callback functions. 2) mouse events are only for mouse not for touch. 3) bind both "touch" and "mouse" events. This is how you work with touch events: https://code.sololearn.com/W6xtrgLM7DnP/?ref=app
22nd Dec 2020, 5:02 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 4
Since you have to bind both events with same code, if you use anonymous functions then you can't reuse that code. If you write a named function, you can simply pass reference to all events. for example: function onStart(){ //some code } el.addEventListener('touchstart', onStart); el.addEventListener('mousedown', onStart);
22nd Dec 2020, 5:08 AM
Raj Chhatrala
Raj Chhatrala - avatar
+ 4
check this I think here you will get your answer https://www.sololearn.com/discuss/2268562/?ref=app
22nd Dec 2020, 6:12 AM
Krish
Krish - avatar
+ 3
Thanks Raj Chhatrala🙏 But what's wrong in using anonymous functions 🙂🙏
22nd Dec 2020, 5:06 AM
Shreyansh
Shreyansh - avatar