DEV Community

Tarun D
Tarun D

Posted on

Generate Random Colors using JavaScript

Suppose if you want to generate a random colour for any element in your HTML and want to use that colour in real-time.

The above code snippet will help you do the needful. This code also has a feature to generate different colours in rgb(???,???,???) format in a time frame say 1-second or n seconds.

  • HTML
<!DOCTYPE html>
<html lang="en">

<head>

  <body><button class="btn">Look how the colors are changing</button>
  </body>
</head>

</html>
Enter fullscreen mode Exit fullscreen mode
  • JavaScript
const randomNumber = (min, max) =>
  Math.floor(Math.random() * (max - min + 1) + min);

const randomColor = () =>
  `rgb(${randomNumber(0, 255)}, ${randomNumber(0, 255)}, ${randomNumber(
    0,
    255
  )})`;

const btn = document.querySelector('.btn');

const assignRandom = () => {
  btn.style.color = randomColor();
  btn.style.backgroundColor = randomColor();
};

assignRandom();
setInterval(assignRandom, 1000);
Enter fullscreen mode Exit fullscreen mode
  • CSS
.btn {
  display: inline-block;
  font-size: 20px;
  font-family: inherit;
  font-weight: 500;
  border: none;
  padding: 10px 20px;
  border-radius: 10rem;
  cursor: pointer;
}
Enter fullscreen mode Exit fullscreen mode

Result will be something like this
Image description

I hope this will help someone.

P.S. This is my first post, hoping for some feedback.

Top comments (1)

Collapse
 
tarun080698 profile image
Tarun D • Edited

Interesting. I did the above-presented piece of code by myself and found it useful for others. I did not check if there is a similar kind of post already. I was just excited and created a sample and published my first post.
Thanks a lot for bringing this to notice. I will keep this in mind.