Home > Blockchain >  autoscroll (like movie credits) but the user can takeover by simply scrolling
autoscroll (like movie credits) but the user can takeover by simply scrolling

Time:01-09

I am looking into creating a website which will serve as a a digital leaflet for a musical theatre. The idea is to have an autoscrolling credits list as landingpage. I've looked at examples on codepen to see how this effect is been achieved. But I would also like the user to interact and scroll themselves if they want to. When they stop scrolling the credits will turn back to autoscroll. I didn't find any example who tackles this issue. Does someone of you know a script (JS, or plain css…) that can help me with this?

CodePudding user response:

The most straightforward way is to set up a requestAnimationFrame() function and increment the value accordingly, then set the scroll position to it. Then add the wheel event to detect when a user scrolls (don't use the 'scroll' event though, it already gets called when you change the scrollTop value of the body), also don't forget to cancel the requestAnimationFrame() function. The code would look something like this:

let body = document.body,
  starter = document.querySelector("h1"),
  scroll_counter = 0,
  scrolled,
  auto_scroll_kicked = false;

starter.addEventListener("click", start_scrolling);

function start_scrolling() {
  auto_scroll_kicked = true;
  body.offsetHeight > scroll_counter
    ? (scroll_counter  = 1.12)
    : (scroll_counter = body.offsetHeight);
  document.documentElement.scrollTop = scroll_counter;
  scroller = window.requestAnimationFrame(start_scrolling);

  if (scroll_counter >= body.offsetHeight) {
    window.cancelAnimationFrame(scroller);
  }
}
window.addEventListener("wheel", (e) => {
  if (auto_scroll_kicked) {
    window.cancelAnimationFrame(scroller);
    scroll_counter = 0;
  }
});

Play with the codepen if you'd like: https://codepen.io/SaltyMedStudent/pen/QWqVwaR?editors=0010

There are many options to use: easing functions and etc, but hope this will suffice for now.

  •  Tags:  
  • Related