Tracking an element's position on screen

Unlock this video and the rest of this course by joining Frontend.FYI PRO .

Until now we have been tracking the distance scrolled within the page or a specific div. The useScroll hook can also help us track the position of an element in the viewport.

In order to track an element, we need to pass in some extra configuration to the hook. Let’s take a look these first.

useScroll(
container:
window,
refundefined

This container property is the scrollable element that you’re tracking the scroll position within.

By default Motion sets this value equal to the window element. You can override this yourself by passing in a ref to any HTML element. Doing that will track the scroll position within that element.

target:
"scrollable area of container",
refundefined

The target property represents the moveable element you are tracking the scroll position of. If you don’t pass in any value, Motion will use the scrollable area of the container as the target.

Just like with the container property, you can also pass in a ref to any HTML element. Doing that will start tracking the visibility of that element within the container. Meaning based on whether this element is in view or not, the scroll values will change.

)

Unlock the full lesson with PRO

Want to read the full lesson? Join Frontend.FYI PRO.

PRO is a one time purchase of €249 that gives you lifetime access to this course, any courses released in the future, and so much more!