skip to Main Content

I need to execute a function when the mouse pauses on an element for 3 seconds.
I tried to do this with the mouseover event, but the problem is that my function is triggered immediately when the mouse enters the element

 element.addEventListener("mouseover", () => {
  setTimeout(() => {
      myFunction()
   },3000)
  })

Is there a way to trigger the mouseover event after the user pauses on the element for 3 seconds?

Is there a better way?, please help me

2

Answers


  1. Rather than mouseover, I’d probably use mouseenter since mouseover fires repeatedly as the mouse moves across the element. Then you can use mouseleave to cancel the timer if the mouse leaves the element before the three seconds are up.

    Something like this:

    const target = document.querySelector(".target");
    let timer = 0;
    target.addEventListener("mouseenter", () => {
        timer = setTimeout(() => {
            timer = 0;
            console.log("Timer fired");
        }, 3000);
        console.log("Timer started");
    });
    target.addEventListener("mouseleave", () => {
        if (timer) {
            clearTimeout(timer);
            timer = 0;
            console.log("Timer cancelled");
        }
    });
    <div>Not a target</div>
    <div>Not a target</div>
    <div>Not a target</div>
    <div>Not a target</div>
    <div class="target">Target </div>
    <div>Not a target</div>
    <div>Not a target</div>
    <div>Not a target</div>

    That example only handles a single element (because timer is a single variable), but if you need to handle multiple, you could maintain a WeakMap using the element as the key and the timer handle as the value. (A WeakMap so that if the elements are removed from the DOM at some point, the map entries for them don’t stick around unnecessarily.)

    Login or Signup to reply.
  2. To achieve that behaviour in your app, you need to combine mouseover and mouseout events.

    The key issue is to reset the timer every time the cursor hovers over an element and leaves it.

    let timeoutId;
    
    element.addEventListener("mouseover", () => {
    //clear any previous timeout
    clearTimeout(timeoutId);
    
    //set a new timeout for 3 seconds
    timeoutId = setTimeout(() => {
        console.log("3 seconds elapsed!");
        myFunction();
    }, 3000);
    });
    
    element.addEventListener("mouseout", () => {
    // clear the timeout if the mouse leaves the element
    clearTimeout(timeoutId);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search