DEV Community

loading...
Cover image for JS: Make things happen OnScroll and create better interactive websites

JS: Make things happen OnScroll and create better interactive websites

devlorenzo profile image DevLorenzo ・Updated on ・1 min read

Hello World! The fourth episode of the series - A CSS/JS trick in 5 minutes - Last Article was about a CSS trick (How to make a website responsive).
Since the last two articles were about a CSS trick, let's show you a Javascript one: How to make things happen on scroll.


The first method to make things happen on scroll is fairly easy:

window.onscroll = function () {
  // Code to happen on scroll here
};
Enter fullscreen mode Exit fullscreen mode

But how underlined this query on stack overflow (I also tried this on a website) its result to cause lag and a longer charging time for the user. So it's better to use an event listener with a flag:

const animateFlag = true

window.addEventListener("scroll", function() {
  if(this.pageYOffset > 0) {
    if(animateFlag) {
      // Code to happen on scroll here
      animateFlag = false;
    }
  }
})
Enter fullscreen mode Exit fullscreen mode

Var animateFlag block the code to rerun every time user scroll.


Hope this helped and thanks for reading!

Please smash that like button to make me understand that you want the series to continue :)

Recommended reading:


Subscribe to our newsletter!

A loooong, and fun, weekly recap for you
Free PDF version of my articles
Highly customizable inbox
That's --> free <-- and you help me!

Discussion (0)

pic
Editor guide