Home  >  Q&A  >  body text

How to use addEventListener correctly?

re2.addEventListener("mouseover", function(){
        const re21 = document.getElementById("reso");
        re21.style.position = "absolute";
        re21.style.top = "50%";
        re21.style.left = "50%";
        console.log("Exiting Listener- mouseOver");

        re3.addEventListener("mouseover", function(){
            const re22 = document.getElementById("reso");
            re22.style.position = "fixed";
            re22.style.top ="0px";
            re22.style.left="0px";
            console.log("Exiting Listener- mouseout");
    
          });

      });

I have an html div element with the id "reso". What I want to do is move the element from point A to point B whenever the mouse reaches it. How can we do this?

When we execute the above javascript code. It only moves once. We then tried wrapping the above code along with some console logs using a loop from i=0 to 10. All logs are printing. But the event listener still only executes once.

Can you help us how to do this?

P粉512363233P粉512363233220 days ago356

reply all(2)I'll reply

  • P粉727416639

    P粉7274166392024-04-02 15:44:08

    You may want to initialize a counter in an external scope outside the event callback function and then increment it each time the event is fired.

    const elm = document.getElementById("reso");
    
    let initialTopPosition = 0;
    let initialLeftPosition = 0;
    
    
    function moveElement() {
      initialTopPosition++;
      initialLeftPosition++;
    
      elm.style.top = `${initialTopPosition}%`;
      elm.style.left = `${initialLeftPosition}%`;
      console.log("Exiting Listener- mouseOver");
    };
    
    elm.addEventListener("mousemove", moveElement);
    #reso {
      background-color: red;
      height: 100px;
      width: 100px;
      display: inline-block;
      position: absolute;
    }

    reply
    0
  • P粉605233764

    P粉6052337642024-04-02 00:31:44

    You can use mousemove event instead of mouseover event. This will allow you to continuously update the element's position as the mouse moves

    const re21 = document.getElementById("reso");
    let isMoving = false;
    
    re21.addEventListener("mousemove", function(event) {
      if (!isMoving) {
        isMoving = true;
        re21.style.position = "absolute";
        re21.style.top = `${event.clientY}px`;
        re21.style.left = `${event.clientX}px`;
      }
    });
    
    re21.addEventListener("mouseout", function() {
      isMoving = false;
    });

    reply
    0
  • Cancelreply