DEV Community

Cover image for Parallax image scroll speed with Nuxt 3 and GSAP πŸ›£οΈβœ¨
Bruna Fusiger
Bruna Fusiger

Posted on

Parallax image scroll speed with Nuxt 3 and GSAP πŸ›£οΈβœ¨

I was having some trouble finding how to create a parallax based on scroll speed in two images on my nuxt 3 website. After some research and trial and error I succeededπŸ₯³. Maybe this will be useful to you πŸŽ‰

Steps I followed:


1- Read this Nuxt GSAP module

Image description
πŸ”πŸ“š


2- Install the module



bun add -D @hypernym/nuxt-gsap


Enter fullscreen mode Exit fullscreen mode

Use your preferred package manager. I'm using bun


3- Add the module in your nuxt.config.ts



// nuxt.config.ts

{
  modules: ['@hypernym/nuxt-gsap']
}



Enter fullscreen mode Exit fullscreen mode

4- Add this configs to your Nuxt GSAP Module



// nuxt.config.ts
gsap: {
    composables: true,
    provide: false,
  },


Enter fullscreen mode Exit fullscreen mode

5- In your app.vue register the ScrollTrigger



<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

onMounted(() => {
  gsap.registerPlugin(ScrollTrigger)
})

</script>


Enter fullscreen mode Exit fullscreen mode


6- In the file where you want to create a parallax image effect, import your GSAP and scrollTrigger in the script configuration



<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
</script>


Enter fullscreen mode Exit fullscreen mode

7- Now Let's create the speed scroll parallax image effect

Contextualizing: The function animates elements with a data-speed attribute, making them move vertically as the user scrolls the page.

  • Higher data-speed = less movement, creating a parallax effect where different elements move at different speeds relative to the scroll position.

Script:



<script setup lang="ts">
import gsap from 'gsap'
import { ScrollTrigger } from 'gsap/ScrollTrigger'

onMounted(() => {
  gsap.to('[data-speed]', {
    y: (i, el) => (1 - Number.parseFloat(el.getAttribute('data-speed'))) * ScrollTrigger.maxScroll(window),
    ease: 'none',
    scrollTrigger: {
      start: 0,
      end: 'max',
      invalidateOnRefresh: true,
      scrub: 0,
    },
  })
})
</script>


Enter fullscreen mode Exit fullscreen mode

Template



<template>
<section>
 <NuxtImg
   data-speed="0.9"
   class="absolute top-50 w-15 -right-6"
   src="my-path.webp"
  />

  <NuxtImg
   data-speed="0.8"
   class="absolute top-50 w-15 -right-6"
   src="my-path.webp"
  />
</section>
</template>


Enter fullscreen mode Exit fullscreen mode

PS.: Check out my reference πŸ”

Hope this helps! :)

Top comments (0)