There are different ways to randomly change the element text color or background color using Javascript:

  1. with Math.random() using Math.round/ceil/floor Demo
  2. with seconds Demo
  3. with seconds and conditions Demo

DEMO 1 | DEMO 2 | DEMO 3

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()!

Working examples

DEMO 1 | DEMO 2 | DEMO 3

You might also like: