DEV Community

Pasquale De Lucia
Pasquale De Lucia

Posted on • Updated on

How to create a fade animation css with Qwik

Fade animation adds a distinctive touch to the user experience on your site. By taking advantage of CSS transitions and IntersectionObserver in Qwik, you can achieve a smooth effect when elements enter the viewport.

On my personal site, I implemented a fade effect using CSS transitions and the IntersectionObserver in Qwik. You can take a look at the animation at this link.

First, we define within the component the signals that will be useful for us to monitor the HTML element and its CSS properties. Inside the useVisibleTask$ hook, we insert the Observer.

export default component$(() => {
  ...
  const sectionRef = useSignal<Element>();
  const sectionIsVisible = useSignal<boolean>(true);

  useVisibleTask$(() => {
    if (sectionRef.value) {
      const observer = new IntersectionObserver(([entry]) => {
        sectionIsVisible.value = entry.isIntersecting;
        if (sectionIsVisible.value) {
          observer.disconnect();
        }
      });

      observer.observe(sectionRef.value);
    }
  });
  ...
});
Enter fullscreen mode Exit fullscreen mode

The code within the useVisibleTask$ hook is executed client-side only and creates an IntersectionObserver that updates the value of the sectionIsVisible signal. This signal will then be used to apply the animation.

In the HTML file, we reference the element we want to animate using the signal sectionRef. With sectionIsVisible, we update the CSS classes.

First, we define these two classes in the global.css file:

Without Tailwind:

animation {
  opacity: 0;
  transition-property: opacity;
  transition-delay: 150ms;
  transition-duration: 700ms;
  transition-timing-function: cubic-bezier(0.4, 0, 1, 1);
}

animation.isVisible {
  opacity: 1;
}
Enter fullscreen mode Exit fullscreen mode

With Tailwind:

.animation {
  @apply opacity-0 transition-opacity ease-in duration-700 delay-150;
}

.animation.isVisible {
  @apply opacity-100;
}
Enter fullscreen mode Exit fullscreen mode

Now we can edit the HTML element to which we want to apply the transition:

<section
  ref={sectionref}
  class={"animation " + sectionIsVisible.value && "isVisible"}
>
  <h2>FADE IN</h2>
</section>
Enter fullscreen mode Exit fullscreen mode

This way, when the HTML element enters the viewport, it will do so through an animation.

Further explore the possibilities for advanced customization and create an engaging user experience.

The complete and slightly more complex code is available in this repository.

Top comments (0)