I have html buttons with individual id’s. My need is to trigger ‘touchstart’ and ‘touchend’ on each button after some time delay. Is it possible? Otherwise I’ll have to rewrite a lot of javascript code.
I have googled but I didn’t get any hint.
I have html buttons with individual id’s. My need is to trigger ‘touchstart’ and ‘touchend’ on each button after some time delay. Is it possible? Otherwise I’ll have to rewrite a lot of javascript code.
I have googled but I didn’t get any hint.
3
Answers
Below is code with
touchstart
andtouchend
event listeners for an element. Your post says you have multiple buttons that need event listeners. If they both carry out the same function you can reuse the functions below. Functionsstart
andend
both havesetTimeout
functions which delays the code inside from running for the specified amount of time.Use
EventTarget.dispatchEvent()
:I’d suggest you do rewrite your code so that you don’t have to trigger such events.
My guess is that you have put some business logic (i.e. code that does something relevant for your app) directly inside event listeners, and now you realized that you need to reuse the same logic in a different situation.
If that’s the case, the correct thing to do is not to try to figure out how to trigger events from code, but instead to extract the logic into separate, reusable functions, that you can then call both from the event listeners and also from a
setTimeout
or similar.