Javascript Style How to - Set CSS value with random color








Question

We would like to know how to set CSS value with random color.

Answer


<!DOCTYPE html>
<html>
<body>
  <div id="foo">Test</div>
<script type='text/javascript'>
<!--  w ww.j a  v a2s .  co m-->
function random_color() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF << 0).toString(16);
}

document.getElementById("foo").style.backgroundColor = random_color();


</script>
</body>
</html>

The code above is rendered as follows: