How to put a delay on the "wheel" event?

94 views Asked by At

So I have this code that upon using a mouse wheel or a touchpad changes the view to the next div in the array of sections. However, when I use the touchpad it does not work properly since at every scroll the index changes. How can I add a delay so that every usage of mouse wheel or touchpad is counted as one scroll. Any suggestions ?

const MainNavigation = () => {
  let index = 0;
  window.addEventListener("wheel", function (event) {
    if (event.deltaY < 0) {
      --index;
    } else if (event.deltaY > 0) {
      ++index;
    }
    scrollToSection();
  });
  const scrollToSection = () => {
    if (index < 0 || index > 2) {
      index = 0;
    }
    console.log(index);
    sections[index].scrollIntoView({ behavior: "smooth" });
  };
};
1

There are 1 answers

0
Dimava On

let sum = 0
div1.addEventListener('wheel', (e) => {
   console.log(e.deltaY)
   sum += e.deltaY
   div2.scrollTo(0, Math.floor(sum / 100) * 100)
})

let sum3 = 0;
div3.addEventListener('wheel', (e) => {
   e.preventDefault()
   console.log(e.deltaY)
   sum3 += e.deltaY
   div3.scrollTo(0, Math.floor(sum3 / 100) * 100)
})
* {
  border: 1px solid black;
}
[h100] {
  height: 100px;
}
[w100] {
  width: 100px;
}
#div1, #div2, #div3 {
  max-height: 300px;
  overflow-y: scroll;
  display: inline-block
}
<div id="div1">
<div h100 w100> 100 </div>
<div h100 w100> 200 </div>
<div h100 w100> 300 </div>
<div h100 w100> 400 </div>
<div h100 w100> 500 </div>
<div h100 w100> 600 </div>
<div h100 w100> 700 </div>
<div h100 w100> 800 </div>
<div h100 w100> 900 </div>
</div>

<div id="div2">
<div h100 w100> 100 </div>
<div h100 w100> 200 </div>
<div h100 w100> 300 </div>
<div h100 w100> 400 </div>
<div h100 w100> 500 </div>
<div h100 w100> 600 </div>
<div h100 w100> 700 </div>
<div h100 w100> 800 </div>
<div h100 w100> 900 </div>
</div>

<div id="div3">
<div h100 w100> 100 </div>
<div h100 w100> 200 </div>
<div h100 w100> 300 </div>
<div h100 w100> 400 </div>
<div h100 w100> 500 </div>
<div h100 w100> 600 </div>
<div h100 w100> 700 </div>
<div h100 w100> 800 </div>
<div h100 w100> 900 </div>
</div>