I am striving to achieve a randomized shine effect on specific text using CSS animation. I currently have a functioning code, but I am interested in learning if there is a more efficient or straightforward solution.
HTML:
<span class="foo">
<span class="bar">
</span>
</span>
CSS:
@keyframes masked-animation {
0% {background-position: -1000px 0}
50% {background-position: 1000px 0}
100% {background-position: 1000px 0}
}
.foo{
text-align: center;
font-size: 40px;
font-weight: bold;
display: block;
color: red;
position: absolute;
}
.bar{
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
color: rgba(0,0,0,0);
background-image: linear-gradient(-45deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.67) 48%, rgba(255,255,255,
0.9) 50%, rgba(255,255,255,0.67) 52%, rgba(255,255,255,0) 100%);
background-repeat: no-repeat;
-webkit-background-clip: text;
animation-name: masked-animation;
animation-timing-function: ease-in-out;
animation-iteration-count: infinite;
background-size: 400% 100%;
}
JS:
$('.foo')[0].childNodes[0].nodeValue = "Text";
$('.foo > .bar').css({
"animation-duration" : 8 + Math.round(Math.random()*40)/10 + "s",
"animation-delay" : Math.round(Math.random()*100)/10 + "s"
}).text("Text");
To ensure the animation displays correctly, it must be placed above the element/text. Placing it on the same element will cause it to appear behind. I attempted to use ::before
, but I encountered difficulty selecting it with JS as it doesn't physically exist in the DOM.
This effect needs to be implemented on multiple elements, and the text inside <span>
changes periodically.