Scroll-Animated Text Highlighting with GSAP and ScrollTrigger for Engaging Web Experiences
an HTML document with GSAP (GreenSock Animation Platform) and ScrollTrigger for animating text on scroll. This script animates each character in the .quote element with a red background when it comes into view.
- Here's a breakdown of your code:
- includ the GSAP library and ScrollTrigger plugin from a CDN
- There's a CSS style for the .spacer class, setting its height to 80% of the viewport height.
- In the body, there are two .spacer divs and an <h1> element with the class .quote.
- The script below uses GSAP to create an animation for each character in the .quote element. It splits the text into individual characters and animates the background color to red with a stagger effect. The animation is triggered when the element comes into view.
<script src="https://unpkg.com/gsap@3/dist/gsap.min.js"> </script>
<script src="https://unpkg.com/gsap@3/dist/ScrollTrigger.min.js"> </script>
<script src="https://unpkg.com/gsap@3/dist/ScrollTrigger.min.js"> </script>
<style>
.spacer {
height: 80vh;
}
</style>
.spacer {
height: 80vh;
}
</style>
<div class="spacer"></div>
<h1 class="quote">At vero eos et accusamus et odio dignissimos ducimus qui blanditiis praesentium volupt.</h1>
<div class="spacer"></div>
<h1 class="quote">At vero eos et accusamus et odio dignissimos ducimus qui blanditiis praesentium volupt.</h1>
<div class="spacer"></div>
<script>
const quotes = gsap.utils.toArray('.quote');
quotes.forEach((quote) => {
quote.innerHTML = "" + quote.innerText.split("").join("") + "";
gsap.to(quote.querySelectorAll(".char"), {
backgroundColor: "red",
ease: "power4.out",
stagger: 0.03,
duration: 0.1,
scrollTrigger: {
trigger: quote,
start: "top center",
toggleActions: "play none none reverse"
}
});
});
</script>