JavaScript is required

Creating a Custom Directive for Animating Elements on Scroll in Nuxt.js 3

To create a custom directive for animating elements on scroll in a Nuxt.js 3 project, you can leverage the Intersection Observer API for detecting when an element comes into view. Below is an example of a custom directive that adds a CSS class to an element when it becomes visible during a scroll.

Plugin File: plugins/animate.js

// plugins/animate.js
export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.vueApp.directive('animate', {
      mounted(el, binding) {
   
    const options = {
      threshold: 0, // Adjust as needed
    };

   const animatedScrollObserver = new IntersectionObserver(
  (entries, animatedScrollObserver) => {
   
    entries.forEach((entry) => {
     
      if(entry.isIntersecting) {
        entry.target.classList.add('enter');
        animatedScrollObserver.unobserve(entry.target);
      }
    });
  }
, options);

          // Start observing the element
          el.classList.add('before-enter');
    animatedScrollObserver.observe(el);
  },

    getSSRProps (binding, vnode) {
      // you can provide SSR-specific props here
      return {}
    }
  })
})

then,

To apply the custom directive for animating elements on scroll within your Nuxt.js 3 components, follow these steps:

1. Include the Directive in the Component

In your component template, use the v-animate directive and provide the CSS class that triggers the desired animation:

<template>
  <div v-animate>
    <!-- Your content here -->
  </div>
</template>

2. Add the css to the App.vue file

In your component template, use the v-animated-scroll directive and provide the CSS class that triggers the desired animation:

App.vue

<style>
.before-enter {
    opacity: 0;
    transform: translateY(100px);
    transition: all 2s ease-out;
}

.enter {
    opacity: 1;
    transform: translateY(0px);
}
</style>

Please share to your friends,
If you like this post

Eyoba
Shaping world class websites, designs and experiences.

Contact

If you have any questions, or want to have a ☕️ with me, please feel free to contact me.