I am trying to make a website which changes its color when a button is pressed. For that, I created an array with colors and got a random colour using Math.floor
. I then used onclick() to change the colour but there is a problem. The color is getting changed but when I press the button again, nothing is happening and to change the colour again, I have to reload the page. I tried using e.preventDefault
in my onclick function but still it isn’t working.
let arr = ["black", "red", "silver", "gray", "white", "maroon", "red", "purple", "fuchsia", "green", "lime", "olive", "yellow", "navy", "blue", "teal", "aqua"]
let item = arr[Math.floor(Math.random() * arr.length)];
console.log(item)
document.getElementById('btn').onclick = function(e) {
document.body.style.background = item
document.getElementById('name').innerHTML = item
e.preventDefault()
}
html {
height: 100%;
width: 100%;
}
#btn {
border: 3px solid green;
margin: auto;
text-align: center;
font-size: 50px;
}
#name{
border: 3px solid green;
margin: auto;
text-align: center;
font-size: 50px;
}
<div id="name">Colour name will appear here</div>
<button id="btn" type="button">Click Me for colour change in background</button>
<script src="script.js"></script>
<script src="https://replit.com/public/js/replit-badge-v2.js" theme="dark" position="bottom-right"></script>
3
Answers
You can put the line of let item = arr[Math.floor(Math.random() * arr.length)]; into the onclick function. You need to reload the page because the item variable only load the value once. If you put into the function, you will load a new value and get new color.
you are only setting item (i.e. the colour to change to) once, so the button only ever changes the colour to this one. This is why you think its doing nothing
Declare the variable outside of the onclick function and on every click assign the new value to the item variable