I've coded a unique effect for my <h1>
heading text where each letter is enclosed in its own <span>
element, like this:
<h1 class='gradient-heading' id='fade'>
<span>H</span>
<span>e</span>
<span>l</span>
<span>l</span>
<span>o</span>
</h1>
To add some flair, I wanted to apply a gradient color to this heading text. Using CSS properties such as background-clip: text
, I made the text transparent and added a gradient background with the following style:
.gradient-heading {
background: linear-gradient(90deg, rgba(239,255,0,1) 0%, rgba(255,182,0,1) 48%, rgba(199,0,255,1) 100%);
background-clip: text;
color: transparent;
}
Now comes the tricky part - fading each individual letter within the <h1>
using JavaScript. I tried implementing an animation with the following script:
function fadeLetters() {
const heading = document.getElementById('fade');
const spans = heading.querySelectorAll('span');
let delay = 0;
let delayIncrement = 200;
let numLettersFadedIn = 0;
const totalLetters = spans.length;
spans.forEach((span, index) => {
setTimeout(() => {
span.style.transition = 'opacity 1s ease-in-out';
span.style.opacity = 1;
numLettersFadedIn++;
if (numLettersFadedIn === totalLetters) {
setTimeout(() => {
spans.forEach((span, index) => {
setTimeout(() => {
span.style.transition = 'opacity 1s ease-in-out';
span.style.opacity = 0;
}, index * delayIncrement);
});
setTimeout(() => {
numLettersFadedIn = 0;
fadeLetters();
}, totalLetters * delayIncrement);
}, delayIncrement);
}
}, delay);
delay += delayIncrement;
});
}
fadeLetters();
However, the animation does not seem to work as expected. The fadeIn/Out effect doesn't occur smoothly - instead, letters blink on and off without transitioning properly. I suspect that this issue may be related to the background-clip: text
CSS property, but I'm unsure of the exact problem.
You can view and test this issue on Codepen here: https://codepen.io/mknelsen/pen/vYVxKeb
If anyone has encountered a similar challenge or can provide insights into why this isn't working correctly, your input would be greatly appreciated!