DEV Community

Discussion on: Using event listeners to create better animations

Collapse
 
bcdbuddy profile image
Babacar Cisse DIA

hey nice animations out there! I love them
but did you thought about debouncing the scroll event listener ? From experience I know this type of events can be very called a huge amount of time

// from npm
import debounce from 'lodash.debounce';

// or self implementation
function debounce(callback, delay){
  var timer;
  return function(){
      var args = arguments;
      var context = this;
      clearTimeout(timer);
      timer = setTimeout(function(){
          callback.apply(context, args);
      }, delay)
  }
}

window.addEventListener('scroll', debounce(function(e) {
  let scrollY = window.scrollY  / window.innerHeight * 5;
  // Create a calculation to base the scale amount on

  // Create min and max values for the scaling:
  if (scrollY <= 0.3) {
    scrollY = 0.3;
    // We don't want the video to become smaller than (scale(0.3))
  }
  if (scrollY >= 1) {
    scrollY = 1;
    // We don't want the video to become bigger than (scale(1))
  }
  videoContainer.style.setProperty('--scale', `${ scrollY }`);
  // Set css variable on the video container
}));