Created
February 8, 2025 17:20
-
-
Save Muzammil-cyber/b9cb8d335139a6cd99de2f50f58004c4 to your computer and use it in GitHub Desktop.
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
"use client"; | |
import { cn } from "@/libs/utils"; | |
import gsap from "gsap"; | |
import ScrollTrigger from "gsap/dist/ScrollTrigger"; | |
import { useWindowSize } from "hamo"; | |
import { useEffect, useRef } from "react"; | |
// use tailwind for styling | |
export function Parallax({ | |
className = "", | |
children, | |
speed = 1, | |
id = "parallax", | |
}: { | |
className?: string; | |
children: React.ReactNode; | |
speed?: number; | |
id?: string; | |
}) { | |
const trigger = useRef<HTMLDivElement>(null); | |
const target = useRef<HTMLDivElement>(null); | |
const timeline = useRef<gsap.core.Timeline | null>(null); | |
const { width: windowWidth = 0 } = useWindowSize(); | |
useEffect(() => { | |
gsap.registerPlugin(ScrollTrigger); | |
const y = windowWidth * speed * 0.1; | |
const setY = gsap.quickSetter(target.current, "y", "px"); | |
timeline.current = gsap.timeline({ | |
scrollTrigger: { | |
id: id, | |
trigger: trigger.current, | |
scrub: true, | |
start: "top bottom", | |
end: "bottom top", | |
onUpdate: (e) => { | |
setY(e.progress * y); | |
}, | |
}, | |
}); | |
return () => { | |
timeline?.current?.kill(); | |
}; | |
}, [id, speed, windowWidth]); | |
return ( | |
<div | |
ref={trigger} | |
className={cn(className, "flex items-end overflow-hidden", { | |
"items-start": speed < 0, | |
})} | |
> | |
<div | |
ref={target} | |
style={{ height: `${100 + 20 * Math.abs(speed)}%` }} | |
className={`w-full`} | |
> | |
{children} | |
</div> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment