Categories
JavaScript Answers

How to add a scroll event listener with JavaScript?

Spread the love

Sometimes, we want to add a scroll event listener with JavaScript.

In this article, we’ll look at how to add a scroll event listener with JavaScript.

How to add a scroll event listener with JavaScript?

To add a scroll event listener with JavaScript, we call addEventListener.

For instance, we write

const runOnScroll = (element) => {
  console.log(element);
};

const elements = [...document.querySelectorAll(`...`)];

elements.forEach((element) => {
  window.addEventListener("scroll", () => runOnScroll(element), {
    passive: true,
  });
});

to call querySelectorAll to select all the elements we want to add a scroll listener to.

Then we use the spread operator to spread the entries into an array.

Next, we call elements.forEach with a callback that calls addEventListener to add a scroll listener to each element in elements.

Conclusion

To add a scroll event listener with JavaScript, we call addEventListener.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *