DEV Community

Cover image for Random background color changer in JavaScript
Manoj Rathod
Manoj Rathod

Posted on

Random background color changer in JavaScript

Demo:- https://codepen.io/iammanojrathod/pen/PoJLQvQ

HTML code: -

<button id="btn">Click me</button>
Enter fullscreen mode Exit fullscreen mode

CSS code: -

body{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
button{
  background: orange;
  color: black;
  outline: none;
  padding: 10px 20px;
  border: 1px solid black;
  border-radius: 10px;
  font-size: 1.5rem;
  cursor: pointer;
  box-shadow: 3px 3px 5px;
}
button:active{
  transform: translate(3px, 3px);
}
Enter fullscreen mode Exit fullscreen mode

JavaScript code: -

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

btn.addEventListener('click', () => {
  document.body.style.background = randomBg();
  console.log(randomBg());
});

function randomBg() {
  return `hsl(${Math.floor(Math.random() * 360)}, 100%, 50%)`;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)