Hey everyone (and Daniele )
I’m trying to make an animation of my homepage working using the page transition (swup), on initial load, the animation is working fine, but when I change pages then go back to the homepage, it’s not working.
As I’m not a seasoned developer, I’ve asked ChatGPT for the code, but unfortunately it’s not working. Here’s the code ChatGPT gave me:
<script>
document.addEventListener('swup:contentReplaced', initScrollAnimation);
function initScrollAnimation() {
const homeHero = document.querySelector('.home-hero');
const homeHeroText = document.querySelector('.home-hero .home-hero_text');
function handleScroll() {
const heroHeight = homeHero.offsetHeight;
const scrollY = window.scrollY;
const scrollPercent = Math.min(scrollY / heroHeight, 1); // Ensure scrollPercent doesn't exceed 1
// Apply blur to the hero section
gsap.to(homeHero, {
duration: 0.5,
ease: 'power1.out',
filter: `blur(${scrollPercent * 20}px)`
});
// Calculate scale and opacity for the text
let scale = 1 - scrollPercent * 0.1; // Adjusted for a minimum of 0.9 scale
let opacity = 1 - scrollPercent;
// Apply scale and opacity to the text
gsap.to(homeHeroText, {
duration: 0.5,
ease: 'power1.out',
scale: Math.max(scale, 0.9), // Ensure scale does not go below 0.9
opacity: Math.max(opacity, 0), // Ensure opacity does not go below 0
transformOrigin: 'center center'
});
}
// Remove any existing scroll listeners to avoid duplicates
window.removeEventListener('scroll', handleScroll);
// Add new scroll listener
window.addEventListener('scroll', handleScroll);
}
// Initial call for the first page load
initScrollAnimation();
</script>
And the original code:
<script>
// Hero Scroll Animation
document.addEventListener("DOMContentLoaded", function () {
const homeHero = document.querySelector('.home-hero');
const homeHeroText = document.querySelector('.home-hero .home-hero_text');
function handleScroll() {
const heroHeight = homeHero.offsetHeight;
const scrollY = window.scrollY;
const scrollPercent = Math.min(scrollY / heroHeight, 1); // Ensure scrollPercent doesn't exceed 1
// Apply blur to the hero section
gsap.to(homeHero, {
duration: 0.5,
ease: 'power1.out',
filter: `blur(${scrollPercent * 20}px)`
});
// Calculate scale and opacity for the text
let scale = 1 - scrollPercent * 0.1; // Adjusted for a minimum of 0.9 scale
let opacity = 1 - scrollPercent;
// Apply scale and opacity to the text
gsap.to(homeHeroText, {
duration: 0.5,
ease: 'power1.out',
scale: Math.max(scale, 0.9), // Ensure scale does not go below 0.9
opacity: Math.max(opacity, 0), // Ensure opacity does not go below 0
transformOrigin: 'center center'
});
}
window.addEventListener('scroll', handleScroll);
});
</script>
Thanks in advance, have a great day