Reputation: 173
This is the js I used:
var bgcolor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
function changeBackground() {
document.body.style.background = bgcolor;
}
And the HTML for the button:
<button onclick="changeBackground();">
The function works, however, it only works once and then does not work again until I refresh the page. I am new to js, is there something I might be missing or doing wrong? Thank you.
Upvotes: 2
Views: 107
Reputation: 21
You are assigning a number to bgcolor only once outside of your function. Try calling that line of code within the function itself, like so:
function changeBackground() {
document.body.style.background = bgcolor;
var bgcolor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
}
Upvotes: 1
Reputation: 30993
bgcolor is in the global scope and calculated once at page start. Insert bgcolor var inside changeBackground function body so its value will be recalculated.
Upvotes: 1
Reputation: 1937
Could you please try this
js
function changeBackground() {
var bgcolor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
document.body.style.background = bgcolor;
}
html
<button onclick="changeBackground();">
Upvotes: 2
Reputation: 1240
You are setting the bgcolor
variable once, after that it never changes. Move the setting inside the changeBackground
function, and it should work.
function changeBackground() {
var bgcolor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
document.body.style.background = bgcolor;
}
Upvotes: 1