Warm tip: This article is reproduced from stackoverflow.com, please click
arrays ecmascript-6 javascript

Using a wheel event to call a function that chooses new variables in the array

发布于 2020-03-27 10:16:16

I have added a wheel event-listener to an HTML element. My array has 4 variables in it. Now, my aim is that whenever the user rolls his mouse wheel/touchpad on the object where the event - listener is added, the next variable should be selected.

For example, my array is like this [apple, orange, papaya, guava]. I want to create something that will choose apple upon wheel movement, then orange upon next wheel movement, then papaya upon next wheel movement and so on.

And the same work in opposite direction (from guava to papaya to arrange for each time user rolls their mouse wheel or scrolls up the touchpad)

The issue I face are these two:

  1. the mouse wheel fires way too many times and calls the function (damnIt) too many times. Even if I write a function to iterate the array in the order I mentioned. The function being called so many times will randomize things.

  2. I am not even sure how to write a function to cause such iteration in the array. This is not my primary problem, as of now.

    var controller = document.querySelector(".main");
    var apple = document.querySelector(".box");
    var orange = document.querySelector(".box1");
    var papaya = document.querySelector(".box2");
    var guava = document.querySelector(".box3");
    var boxes = [apple,orange,papaya,guava];
    
    controller.addEventListener('wheel', damnIt);
    
    function damnIt(){
        console.log ("hey");
        //my function for array selection goes here
    }
    
Questioner
Bon Leofen
Viewed
170
Vladislav Sevostyanov 2019-07-03 22:38

Trotting way (Call no more than once every 150 ms):

var controller = document.querySelector(".main");
var apple = document.querySelector(".box");
var orange = document.querySelector(".box1");
var papaya = document.querySelector(".box2");
var guava = document.querySelector(".box3");
var boxes = [apple,orange,papaya,guava];

controller.addEventListener('wheel', throttle(damnIt, 150));

function damnIt() {
  console.log ("hey");

    //my function for array selection goes here
}

function throttle(cb, timeout) {
  // You can rewrite this function by replacing the time limit with the
  // scroll pitch. I think that would be the best solution.
  // let delta = e.deltaY || e.detail || e.wheelDelta;
  // ... sum delta and call callback by the number of steps: accumulator/step

  let lastCall = 0;

  return function() {
    if (new Date() - lastCall > timeout) {
      lastCall = new Date();

      cb();
    }
  }
}