How to disable addEventListener with mousewheel event

Viewed 134

I'm creating a horizontal scroll website and wondering if I can make the addEventListener disable when the cursor pointer is located within an element.

Here is an example.

<div class="bar">Disable mousewheel event when the cursor pointer is within this div</div>

<script>
window.addEventListener("mousewheel", (e) => {

   if (e.deltaX === 0) {
      e.stopPropagation();
      e.preventDefault();
      window.scrollBy(e.deltaY, 0);
   }
});
</script>

1 Answers

The key is not about "disabling" or "removing" the event listener...

The key is knowing if the mouse is over a particular element in order to do something else...
(actually, doing nothing should be considered "something else").

let barFlag = false;

window.addEventListener("mousewheel", (e) => {
  if(!barFlag){
    console.log("mousewheel!")
  }else{
    console.log("No!")
  }
});

document.querySelectorAll(".bar").forEach(function(bar){
  bar.addEventListener("mouseenter", function(){
    barFlag = true;
  });
  bar.addEventListener("mouseleave", function(){
    barFlag = false;
  })
})
.spacer{
  height: 500px;
}
.bar{
  height: 300px;
  border: 1px solid red;
}
<div class="spacer"></div>

<div class="bar">Disable mousewheel event when the cursor pointer is within this div</div>

<div class="spacer"></div>

<div class="bar">Disable mousewheel event here too</div>

<div class="spacer"></div>

Related