Categories
JavaScript Answers

How to Check if an Element is Visible After Scrolling?

Spread the love

Checking if an element is visible after scrolling is something that we may have to do sometimes.

In this article, we’ll look at how to check if an element is visible after scrolling with JavaScript.

Create Our Own Function

We can create our own function to check if an element is visible after scrolling.

For instance, we can write the following HTML:

<div>
</div>

And the following JavaScript:

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

const isScrolledIntoView = (el) => {
  const {
    top,
    bottom
  } = el.getBoundingClientRect();
  const elemTop = top;
  const elemBottom = bottom;
  const isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
  return isVisible;
}

const el = document.querySelector('#el-50')
document.addEventListener('scroll', (e) => {
  console.log(isScrolledIntoView(el))
})

We get the div element with querySelector .

Then we have a for loop to insert p elements into the div.

We set the id property so that we can get the inserted element later.

Next, we create the isScrolledIntoView function to check if the element is in the browser screen.

To do this, we call el.getBoundingClientRect to get the top and bottom coordinates of the element.

These are top and bottom y coordinates respectively.

Then we return the isVisible variable, which we create by checking if top is bigger than or equal to 0 and the bottom is less than or equal to the innerHeight of window.

If both conditions are true, then we know the element is in the window.

Then we get the element we want to watch with another querySelector call.

And finally, we call addEventListener to add the scroll event to the document and call the isScrolledIntoView function with the el element to see when el is in the browser window.

As we scroll down, we should see the logged value goes from false to true and back to false .

Using the IntersectionObserver API

The IntersectionObserver API is an API available in recent browsers to let us check whether an element is visible on the screen.

For instance, we can write:

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

const onIntersection = (entries, opts) => {
  entries.forEach(entry => {
    const visible = entry.intersectionRatio >= opts.thresholds[0]
    console.log(entry.intersectionRatio.toFixed(2), visible)
  })
}

const intersectionObserverOptions = {
  root: null,
  threshold: .5
}

const observer = new IntersectionObserver(onIntersection, intersectionObserverOptions)
const target = document.querySelector('#el-50')
observer.observe(target)

The first querySelector call and the for loop is the same as before.

Then we define the onIntersection function that takes the entries and opts parameters.

entries is the elements we’re watching for visibility with.

And opts is an options object that has the thresholds property to get the threshold of intersection with the screen.

In the forEach callback, we have the the visible variable, which we create by comparing the intersectionRatio of entry with the first threasholds value in opts ,

We know it’s visible if the intersectionRatio is bigger than the threshold.

Then we log the visible value and the intersectionRatio .

Next, we have the interswedtiobnObserverOptions to set the threshold of the intersection in order for it to be visible.

Then we pass them both to the IntersectionObserver constructor.

Then we call observer.observe with the target element to watch whether it’s visible or not.

Conclusion

We can compare the position of the element or use the IntersectionObserver API to check whether an element is visible or not after scrolling.

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 *