Categories
JavaScript Answers

How to Add an Event listener for When an Element Becomes Visible with JavaScript?

Spread the love

We can use the IntersectionObserver API to watch when an element is visible or not.

For instance, if we have the following HTML:

<div>

</div>

Then we can add the following JavaScript:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  p.id = `el-${i}`
  div.appendChild(p)
}

const options = {
  rootMargin: '0px',
  threshold: 1.0
};

const observer = new IntersectionObserver((entries, observer) => {
  entries.forEach(entry => {
    console.log(entry.intersectionRatio > 0 ? 'visible' : 'invisible');
  });
}, options);

const element = document.querySelector('#el-50')
observer.observe(element);

to add elements into the div with the for loop.

Then we use the IntersectionObserver constructor to add the intersection observer.

The options object has the rootMargin which is the margin for when the element is considered to be visible.

threshold is how much of the element is visible on the screen for it to be considered visible.

This value is between 0 and 1.

We pass in a callback into IntersectionObserver which runs when the element we’re watching appears or disappears from the screen.

We loop through entries to get the intersection entries object.

And we log entry.intersectionRatio and check if it’s bigger than 0 to see if the element we’re watching is visible.

Finally, we call observer.observe to watch the element with ID el-50 to be visible or invisible on the screen.

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 *