javascripthtmlremoveeventlistener

How to remove event listener in javascript


I want to remove the event listener event when image is not in mousemove position (or not in hover state). i am new in javascript due to this reason unable to solve this issue. any help is highly appreciated. Here is my code:

const image = document.querySelector("img");

image.addEventListener("mousemove", event => {

  const { top, bottom, left, right } = event.target.getBoundingClientRect();

  const middleX = (right - left) / 5;
  const middleY = (bottom - top) / 5;

  const clientX = event.clientX;
  const clientY = event.clientY;

  const offsetX = (clientX - middleX) / middleX;
  const offsetY = (middleY - clientY) / middleY;

  event.target.style.transform = `perspective(1000px) rotateY(${offsetX *
    5}deg) rotateX(${offsetY * 5}deg) scale3d(1, 1, 1)`;
    

});
image.removeEventListener("mousemove", event);
div.my-img {
  margin: 5rem 25%;
  width: 100%;
  position: relative;
}

img {
  position: absolute;
  top: 0px;
  left: 0px;
  width: 50%;
  height: auto;
  object-fit: cover;
  object-position: center center;
  opacity: 1;
  border-radius: 8px;
  cursor: pointer;
}
<div class="my-img">
  <img class="tilt" src="https://images.unsplash.com/photo-1542856391-010fb87dcfed"></div>


Solution

  • This sounds like an X/Y problem

    You RARELY need to remove an event listener. If you want to reset the transform when we move the mouse out, then this code will work

    const image = document.querySelector("img");
    image.addEventListener("mouseleave", event => {event.target.style.transform = 'none'; });
    
    image.addEventListener("mousemove", event => {
      const { top, bottom, left, right } = event.target.getBoundingClientRect();
      const middleX = (right - left) / 5;
      const middleY = (bottom - top) / 5;
      const clientX = event.clientX;
      const clientY = event.clientY;
      const offsetX = (clientX - middleX) / middleX;
      const offsetY = (middleY - clientY) / middleY;
      event.target.style.transform = `perspective(1000px) rotateY(${offsetX *
        5}deg) rotateX(${offsetY * 5}deg) scale3d(1, 1, 1)`;
    });
    div.my-img {
      margin: 5rem 25%;
      width: 100%;
      position: relative;
    }
    
    img {
      position: absolute;
      top: 0px;
      left: 0px;
      width: 50%;
      height: auto;
      object-fit: cover;
      object-position: center center;
      opacity: 1;
      border-radius: 8px;
      cursor: pointer;
    }
    <div class="my-img">
      <img class="tilt" src="https://images.unsplash.com/photo-1542856391-010fb87dcfed"></div>