Random Background Color using JavaScript

0
963

In this post, we will be writing a simple JavaScript function that will generate random color which we set as the background of webpage.

Source Code :

<body onclick="changeColor();">

</body>


<script type="text/javascript">
  function generateColor(){
    length = 6;
    var chars = 'abcdef0123456789';
    var color = '';
    if(length > 0){
      for(var i=0; i < length; i++){
          color += chars.charAt(Math.floor(Math.random() * chars.length));
      }
    }
    return '#'+color;
  }

  function changeColor(){
    document.body.style.backgroundColor = generateColor();
  }

  changeColor();
</script>

 
Follow this video for complete guidance :

Comments are closed.