DEV Community

Joe 🏴󠁧󠁢󠁷󠁬󠁳󠁿
Joe 🏴󠁧󠁢󠁷󠁬󠁳󠁿

Posted on

Tailwind + IntersectionObserver API = <3

The intersection observer is an incredibly powerful API, and really great for managing scrolling animations. When combined with Tailwind, it gets even better.

In my use case, I have multiple elements which need to fade in once they are in the viewport, but their transition time should vary to give a sense of speed and progression.

To achieve the varying animation speeds, you could do a few things:

  • Use inline styling
  • Write a class for each element
  • use the attr() method in CSS

My project is using Tailwind and Vue, so I opted for a tailwind class-based solution.

Let's have a look at my observe:

observeHandler(ob) {
      ob.forEach((el) => {
        el.target.style.opacity = ob[0].intersectionRatio;
      });
    },
Enter fullscreen mode Exit fullscreen mode

Pretty simple stuff. We are using the intersection ratio to calculate the opacity of the element, to fade in on scroll.

I've got a lot of elements to observe, here's my solution in attaching the observe:

let options = {
  root: document,
  rootMargin: '0px',
  threshold: [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]
}

let observer = new IntersectionObserver(this.observeHandler, options);

let els = document.querySelectorAll('[data-observe]');

els.forEach((el) => {
  observer.observe(el);
});
Enter fullscreen mode Exit fullscreen mode

Amazing, nice and simple. We seek elements with the data-observe attribute:

<div class="text-5xl mb-5" data-observe>Websites are more than code.</div>
Enter fullscreen mode Exit fullscreen mode

Now, back to our delays and transition speed. I am using Tailwind classes to manipulate those properties, here is a great example:

<div class="flex items-center delay-75" data-observe>
  <div class="w-10 h-1 bg-black mr-3 mt-1"></div>
  <div class="text-2xl">I capture the imagination,</div>
</div>
<div class="flex items-center delay-300 duration-300" data-observe>
  <div class="w-10 h-1 bg-black mr-3 mt-1"></div>
  <div class="text-2xl">hand-craft experiences</div>
</div>
<div class="flex items-center delay-500 duration-500" data-observe>
  <div class="w-10 h-1 bg-black mr-3 mt-1"></div>
  <div class="text-2xl">and build solutions.</div>
</div>
Enter fullscreen mode Exit fullscreen mode

This means I can add any number of observers, and use tailwind to control speed, which is amazing.

Animation example

To see the final result:

https://imgur.com/pdvkqjH

Top comments (0)