Random color background JavaScript

Generate random background color with JS

·

2 min read

Table of contents

Hi!

This time I will try to create radom background color generator. This can be nice addition to any simple game, where you can switch background color with every user click.

HTML

Here we will only need background and button.

<div class="back-color">
    <button id="generate">Click!</button>
  </div>

CSS

For the styles we make our background full screen and center button.

.back-color{
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: aqua;
}
#generate{
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border-radius: 50px;
  border: none;
  width: 100px;
  height: 100px;
  font-weight: 900;
  font-size: 1.5rem;
  cursor: pointer;
}

JS

We will generate our color as RGB value. So we will need 3 random numbers from 0 to 255. I created a function that will return 3 random numbers in that range as an array.

Next we add event listener to our button and save our numbers as a proper RGB value. Lastly we change the background of our div container.

const colors_container = document.querySelector('.back-color')
const generate_btn = document.getElementById('generate')

function generateRandomNumber(){ //0-255
  let numbers = []
  for(let i=0; i<3; i++){
    numbers[i] = Math.floor(Math.random() * 255)
  }
  return numbers
}

generate_btn.addEventListener('click', ()=>{
  let numbers = generateRandomNumber()
  let color_value = 'rgb(' + numbers[0] + ',' + numbers[1] + ',' + numbers[2] + ')'

  colors_container.style.backgroundColor = color_value
})

If you find any mistakes or you have ideas how to refactor my solutions to be simpler/ better please let me know :)

Did you find this article valuable?

Support knowledge blog by becoming a sponsor. Any amount is appreciated!