Intersection Observer for scroll to top buttons, or anything StiCKy

At work, I was working on adding ‘back-to-top’ scroll button feature for when the user scrolls below the fold, and wants to get back to the top of the page without using their mouse and clicking through all that space on the scrollbar.

At first, I wanted to write a conditional JS statement that uses something like — but that doesn’t account for users who have BIG OLE screens. Using hardcoded values don’t account for this.

Instead, the lead developer introduced me to the Intersection Observer API. It is built into modern browsers (except for IE), that asynchronously observes changes in the intersection of a target element.

Here’s a great example of how you would use it.

const headerEl = document.querySelector('.header')
const sentinalEl = document.querySelector('.sentinal')
const handler = (entries) => {
// entries is an array of observed dom nodes
// we're only interested in the first one at [0]
// because that's our .sentinal node.
// Here observe whether or not that node is in the viewport
if (!entries[0].isIntersecting) {
} else {
// create the observer
const observer = new window.IntersectionObserver(handler)
// give the observer some dom nodes to keep an eye on

The JS in the code pen asynchronously observes for changes in entries when there is a change in the screen, with the help of the Intersection Observer. It is called all the way in the end.

For this case, is fired when there is a scroll action is noticed. The returns false.

The property is a Boolean value which is if the target element intersects with the intersection observer's root. If this is , then, the describes a transition into a state of intersection; if it's , then you know the transition is from intersecting to not-intersecting.

If we were viewing the target on the page, we are intersecting. Even if it is partial. If we scroll past it, it is not intersecting, creating a false value.

That’s all for now!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store