DEV Community

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

Posted on • Edited on

6 3

JS: Make things happen OnScroll and create better interactive websites

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!

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay