Categories
JavaScript Answers

How to add an event listener for when element becomes visible with JavaScript?

Spread the love

Sometimes, we want to add an event listener for when element becomes visible with JavaScript.

In this article, we’ll look at how to add an event listener for when element becomes visible with JavaScript.

How to add an event listener for when element becomes visible with JavaScript?

To add an event listener for when element becomes visible with JavaScript, we can use the IntersectionObserver constructor.

For instance, we write

const options = {
  root: document.documentElement,
};

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach((entry) => {
    callback(entry.intersectionRatio > 0);
  });
}, options);

observer.observe(element);

to create an IntersectionObserver object with a callback and the options object.

The callback is run when the element we’re watching changes.

We get the element that intersects the element we’re watching with entries.

We set options.root to the root level element that we’re watching for element visibility for.

Conclusion

To add an event listener for when element becomes visible with JavaScript, we can use the IntersectionObserver constructor.

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 *