Dr. Owning
Dr. Owning

Reputation: 173

JS function only plays once (until refreshed)

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

Answers (4)

Alex Caradonna
Alex Caradonna

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

Irvin Dominin
Irvin Dominin

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

Alexey Sh.
Alexey Sh.

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

Alasjo
Alasjo

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

Related Questions