skip to Main Content

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


  1. Below is code with touchstart and touchend 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. Functions start and end both have setTimeout functions which delays the code inside from running for the specified amount of time.

    document.addEventListener('DOMContentLoaded', load, false); // event listener for page fully loading
    
        function load() { // function called when page laods
            var element = document.getElementById("element");
    
            element.addEventListener("touchstart", start, false);
            element.addEventListener("touchend", end, false);
        }
    
        function start(e) { // function passed in event listener with "e" object
            setTimeout(() => {
                // code here
            }, 1000); // waits 1 second (1000ms) to run code
        }
    
        function end(e) { // function passed in event listener with "e" object
            setTimeout(() => {
                // code here
            }, 1000); // waits 1 second (1000ms) to run code
        }
    
    Login or Signup to reply.
  2. Use EventTarget.dispatchEvent():

    touchstart.addEventListener('touchstart', () => console.log('touchstart'))
    touchend.addEventListener('touchend', () => console.log('touchend'))
    
    setTimeout(() => {
      touchstart.dispatchEvent(new Event('touchstart'));
      touchend.dispatchEvent(new Event('touchend'));
    }, 1000)
    <button id="touchstart">touchstart</button>
    <button id="touchend">touchend</button>
    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search