user9817230
user9817230

Reputation:

How to randomly change the background color of the button by clicking on it?

I have a button, which is fully covering my HTML page and by clicking on it the backgroundColor of a button should change to a different color.

I have already tried to use this code: "Math.floor(Math.random()*16777215).toString(16)" from different sources, but I guess I don't completely understand where to use it.

**JS:**
var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementsById("mainButton").style.background = randomColor;


**HTML:**
<button id="mainButton">click</button>

**CSS:**
#mainButton{
  background-color: white;
  font-family: monospace;
  border: none;
  width: 100%;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
}

Is there anything that would help me? Thanks!

Upvotes: 0

Views: 5333

Answers (3)

X 47 48 - IR
X 47 48 - IR

Reputation: 1498

let button = document.getElementsByTagName('button')[0];

function RBC (e) {
  button.style.backgroundColor = '#'+Math.floor(Math.random()*16777215).toString(16);
}

button.addEventListener("click", RBC);
window.onload = RBC();
button {
  display:block;
  margin:auto;
  height:35px;
  width:95%;
  text-shadow:1px 1px 0.5px #000;
  border:solid 1px #000;
  font-size:18px;
  color:#ccc;
  cursor:pointer;
}
<button>Click Here</button>

Upvotes: 1

Isaac Vidrine
Isaac Vidrine

Reputation: 1666

There's a couple things wrong here:

1) Its getElementById not getElementsById.

2) Instead of setting the style property directly, you need to set style.backgroundColor

3) Your randomColor will result in a hex value, you need to add '#' to the beginning.

Here is a working example

var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById("mainButton").style.backgroundColor = '#' + randomColor;
#mainButton{
  background-color: white;
  font-family: monospace;
  border: none;
  width: 100%;
  height: 100%;
  position: absolute;
  right: 0;
  top: 0;
}
<button id="mainButton">click</button>

Upvotes: 2

Kelvin Aitken
Kelvin Aitken

Reputation: 443

There is a fairly simple demo on W3Schools that shows you how to create a random colour:

https://www.w3resource.com/javascript-exercises/javascript-math-exercise-40.php

In your case, instead of changing the body background colour you would target the button and change that. Something like:

 const myBtn = document.getElementByID("mybutton");
 myBtn.style.backgroundColor = bgColor;

Upvotes: 0

Related Questions