There are different ways to randomly change the element text color or background color using Javascript:
- with
Math.random()
usingMath.round/ceil/floor
Demo - with seconds Demo
- with seconds and conditions Demo
HTML
<!DOCTYPE html>
<html>
<head><title>Javascript Random Color</title></head>
<body>
<p id="clr">change text/background color randomly</p>
</body>
</html>
Javascript
var color_text= document.getElementById('clr');
var color_ary = new Array('F90','60F','6C0','03C','C30','0F0','90F','06F','300','990'); // array of 10 colors
// with Math.random() using Math.round/ceil/floor
function colr() {
//color_text.style.color = '#' + color_ary[ Math.round ( Math.random() * color_ary.length ) ];
color_text.style.color = '#' + color_ary[ Math.ceil ( Math.random() * color_ary.length ) ];
//document.bgColor = '#' + color_ary[ Math.floor ( Math.random() * color_ary.length ) ];
setTimeout('colr()', 1000); // 1 second
}
// HEX colors instead predefined colors
function colr() {
var hexChars = '0123456789ABCDEF'.split(''); // will split each character
var hexColor = '#';
for (var i = 0; i < 6; i++ ) {
hexColor += hexChars [Math.round(Math.random() * 15)]; // 0..15 = 16 hex range
}
color_text.style.color = hexColor;
setTimeout('colr()', 1000);
}
// with seconds
function colr() {
var d = new Date();
var sec = d.getSeconds() % 10;
color_text.style.color = '#' + color_ary[sec];
setTimeout('colr()', 1000);
}
// with seconds and conditions
function colr() {
var d = new Date();
var sec = d.getSeconds() % 10;
if (sec <= 9) {
color_text.style.color = '#' + color_ary[sec];
}
setTimeout('colr()', 1000);
}
Finally load whichever function you liked!
window.addEventListener('onload', colr());
You can pick any of the function call you like. For one of my projects I preferred to use ‘WITH SECONDS’ option! But mostly I prefer Math.random()!
April 13, 2016 at 6:04 pm
is there a way to do this but with fonts?
April 15, 2016 at 12:02 pm
@ping,
Random font face/family with javascript:
var element = document.getElementById(id);
var fonts = [‘arial’, ‘sans-serif’, ‘monospace’, ‘consolas’];
function randomize(){
element.style.fontFamily = fonts[Math.ceil(Math.random() * fonts.length)];
setTimeout(‘randomize()’, 1000);
}
window.addEventListener(‘onload’, randomize());