0

I'm hoping to get a GSAP animation to play ONCE when scrolling, but it seems if the user scrolls, let's say 20px on a long swipe on the touchpad or mouse wheel, it's playing 20 times. How can I limit this in the wheel event in Javascript.

I've added some code below as an example:

let isAnimating = false;
window.addEventListener('wheel', (event) => {
  if (!isAnimating) {
    isAnimating = true;
    slideTimelines[0].play(0).then(() => {
      isAnimating = false;
    });
  }
});
Jake
  • 37
  • 5

1 Answers1

1

Actually you want to detect when scrolling is over. That way you fire it once for every scrolling dynamic. So the question is when a scroll is considered done, as there is no event for that. So let's say 250ms. Credit to this answer

function onwheelend() {
  did_once = false;
}

var timeout_id;
var did_once = false;
window.addEventListener('wheel', (event) => {
  clearTimeout(timeout_id);
  timeout_id = setTimeout(onwheelend, 250);

  if (!did_once) {
    my_action()
    did_once = true;
  }
});


function my_action() {
  console.log("once per wheel event")
}
<div style="height:30000px">keep scrolling</div>
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • This works great, however, it waits for the wheel to finish, for example if the user scrolls down by 100px on a long swipe of the trackpad it will wait for it to go from 1-100 on the delta. – Jake Aug 10 '22 at 20:43
  • That's the event firing we can't control. Maybe `scroll` event would do better? – IT goldman Aug 10 '22 at 20:49
  • Sure, understood. Thing is, it's a custom slider and the page can't scroll as it's 100% of the viewports height and width - I can try that, but I don't think it will work as there's no leeway to scroll. – Jake Aug 10 '22 at 21:55