How to use addEventListener correctly?
P粉512363233
P粉512363233 2024-04-01 17:35:47
0
2
368

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粉512363233
P粉512363233

reply all(2)
P粉727416639

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;
}
P粉605233764

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;
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template