How to animate text underlining with the Intersection Observer API

(This came up recently in a client project and I thought it was a fun (and fairly straightforward) example of the Intersection Observer JavaScript API.)

So you want to underline some text when some event happens. Either on hover or when it enters the viewport.

In the former case, it’s easy to do using plain CSS and the :hover pseudo-selector:

(The above code is a modified version of a snippet found on 30secondsofcode.)

Nothing earth-shattering there. But what if we want to animate the underline when the element enters the viewport? That’s a job for the Intersection Observer API. In a nut, this API lets you listen for events that fire when elements intersect with an ancestor or the document itself. In this case, we want to listen for when our matching elements enter the viewport.

Intersection Observer to the Rescue

Since we’re not listening for hover events, it’s easist to change the animation selector to a second class, so let’s replace :hover with .animate in the second selector:

Now, we add a bit of JavaScript to create observers for elements with the class underline and listen for when they enter the viewport:

First, we define a callback function handleIntersect. This function will run whenever the observed element intersects with the ancestor element defined in the options object (the viewport, in this case).

Then, we initialize an IntersectionObserver object for each of the page elements with the class .underline, and pass it the root and threshold parameters. In English, these options say, ‘run the callback function whenever this element enters the viewport and is 100% visible.’

Once the callback runs, it adds the animate class to the element in quesiton, which starts to transition the background-size property.

Leave a Comment

Scroll to Top