nivi nivi - 2 months ago 8
HTML Question

random letter blinking effect [with diff font colors]

Okay, so I'm in the process of making a web page for myself/for fun and I wanted the title on the web page to have like a blinking effect. like, think of a light bulb and its flickering, but I wanted random letters to flicker as well. I know this might involve some java script and I'm not that great with it yet and I couldn't find examples so I thought I'd try this place out and see if someone can help me?
so, I'm using inspiration from a cartoon here's the link: https://youtu.be/No_omXE6TK0?t=14s
I kinda wanted it to look like that with the flickering. Thanks in advance!!

Answer

In case of you can't run the snippet, here is the fiddle: https://jsfiddle.net/8m667mj4/

var string = x.innerHTML;
var aBlinkingString = "";
for (i = 0; i < string.length; i++) {
    aBlinkingString += "<span class='blink'>" + string[i] + "</span>";
}
x.innerHTML = aBlinkingString;
colors = ["red", "green", "blue"];
setInterval(function() {
            document.querySelectorAll(".blink")[Math.round((document.querySelectorAll(".blink").length - 1) * Math.random())].style.color = colors[Math.round((colors.length - 1) * Math.random())];
            }, 10)
<h1 id="x">
THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
</h1>

I set the h1 element's id to x so I can access it in DOM later.

In the for loop, I wrap every letter in the h1 element in a span element.

Then, I access a random span element and change its color randomly.

See this http://stackoverflow.com/questions/5915096/get-random-item-from-javascript-array to know how to pick random element from array and http://www.w3schools.com/jsref/prop_style_color.asp to know how to set color of an element.

Comments