Created
December 12, 2024 10:43
-
-
Save supahfunk/f0d112c50b44605243555d79982d88b6 to your computer and use it in GitHub Desktop.
GSAP scrollThroughArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*------------------------------ | |
ADD GSAP | |
------------------------------*/ | |
const script = document.createElement('script') | |
script.src = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js' | |
script.onload = () => { | |
console.log('GSAP loaded') | |
} | |
document.head.appendChild(script) | |
const script2 = document.createElement('script') | |
script2.src = 'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/ScrollToPlugin.min.js' | |
script2.onload = () => { | |
console.log('ScrollToPlugin loaded') | |
} | |
document.head.appendChild(script2) | |
gsap.registerPlugin(ScrollToPlugin) | |
/*------------------------------ | |
ADD SCROLL THROUGH ARRAY | |
------------------------------*/ | |
let activeScrollListener = null // Variabile per salvare il listener attivo | |
function scrollThroughArray(array) { | |
// Se esiste un listener attivo, rimuovilo | |
if (activeScrollListener) { | |
document.removeEventListener('keydown', activeScrollListener) | |
} | |
let currentIndex = 0 | |
// Nuovo listener per la tastiera | |
const newScrollListener = (event) => { | |
if (event.key === 'ArrowRight') { | |
// 'ArrowRight' è il codice per la freccia avanti | |
// Scorri all'indice corrente | |
gsap.to(window, { | |
duration: 1.5, | |
scrollTo: { y: array[currentIndex] }, | |
ease: 'power3.inOut' | |
}) | |
// Incrementa l'indice e fai il loop | |
currentIndex = (currentIndex + 1) % array.length | |
} | |
} | |
// Aggiungi il nuovo listener | |
document.addEventListener('keydown', newScrollListener) | |
// Aggiorna la variabile per tracciare il listener attivo | |
activeScrollListener = newScrollListener | |
} | |
/*------------------------------ | |
ESEMPIO | |
------------------------------*/ | |
const data = [780, 1634] | |
const lifestyle = [794, 1640, 2220] | |
const design = [791, 1362, 2153, 2942] | |
scrollThroughArray(data) | |
// Puoi successivamente richiamare: | |
// scrollThroughArray(lifestyle); | |
// scrollThroughArray(design); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment