Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

trigger count up animations only when scrolled into view

Joshen Lim27155e88d86f
diff --git a/www/components/CountUp.tsx b/www/components/CountUp.tsx
index dfee14a7ea5..3e5f12f98e3 100644
--- a/www/components/CountUp.tsx
+++ b/www/components/CountUp.tsx
@@ -3,28 +3,48 @@ import { useState, useEffect } from 'react'
type Props = {
children: any
duration?: number
+ triggerAnimOnScroll?: boolean
+ referenceElId?: string
}
const easeOutQuad = (t: number) => t * (2 - t)
const frameDuration = 1000 / 60
const CountUp = (props: Props) => {
- const { children, duration = 2000 } = props
+ const { children, duration = 2000, triggerAnimOnScroll = false, referenceElId = '' } = props
const countTo = parseInt(children, 10)
- const [count, setCount] = useState(0)
+ const [count, setCount] = useState<number>(0)
+ const [animTriggered, setAnimTriggered] = useState<boolean>(false)
useEffect(() => {
let frame = 0
const totalFrames = Math.round(duration / frameDuration)
-
- const counter = setInterval(() => {
- frame++
- const progress = easeOutQuad(frame / totalFrames)
- setCount(countTo * progress)
-
- if (frame === totalFrames) clearInterval(counter)
- }, frameDuration)
- }, [])
+
+ async function handleScroll() {
+ const reference = document.getElementById(referenceElId)
+ if (reference && !animTriggered) {
+ const yOffset = reference.getBoundingClientRect().top - window.innerHeight + 20
+ if (yOffset <= 0) {
+ setAnimTriggered(true)
+ setCount(0)
+ const counter = setInterval(() => {
+ frame++
+ const progress = easeOutQuad(frame / totalFrames)
+ setCount(countTo * progress)
+
+ if (frame === totalFrames) clearInterval(counter)
+ }, frameDuration)
+ }
+ }
+ }
+
+ if (triggerAnimOnScroll) window.addEventListener('scroll', handleScroll, { passive: true })
+
+ return () => {
+ if (triggerAnimOnScroll) window.removeEventListener('scroll', handleScroll)
+ }
+
+ }, [animTriggered])
return <span>{Math.floor(count)}</span>
}
diff --git a/www/pages/beta.tsx b/www/pages/beta.tsx
index c5ffb0323fb..c22380e9741 100644
--- a/www/pages/beta.tsx
+++ b/www/pages/beta.tsx
@@ -142,7 +142,7 @@ const Introduction = () => {
</p>
</div>
- <div className="col-span-12 grid grid-cols-12 gap-y-12 lg:gap-y-20 mb-20">
+ <div id="alphaNumbers" className="col-span-12 grid grid-cols-12 gap-y-12 lg:gap-y-20 mb-20">
{AlphaNumbers.map((stat: any, idx: number) => (
<div
key={`stat_${idx}`}
@@ -155,7 +155,7 @@ const Introduction = () => {
</div>
<div className="col-span-4 sm:col-span-9 xl:col-span-10">
<p className="text-5xl lg:text-6xl">
- <CountUp>{stat.value}</CountUp>
+ <CountUp triggerAnimOnScroll={true} referenceElId="alphaNumbers">{stat.value}</CountUp>
{stat.unit && <span className="text-2xl ml-1">{stat.unit}</span>}
</p>
</div>