Simon Be
Simon Be

Reputation: 209

Randomly change background image

I'm working on a way to change the background pattern of the body on each click of a button.

I got that code so far, but when I click on the button, the background just turns white. Where is my mistake?

var patternImage = ['01','02','03','04'];
var randomNumber = Math.floor(Math.random() * patternImage.length);

$("#patternSwitcher").click(function(){
    $("body").css("background","url(../images/ + patternImage[randomNumber] + .gif)")
});

Upvotes: 2

Views: 948

Answers (2)

theabraham
theabraham

Reputation: 16370

The string needs to be concatenated:

$("body").css("background","url(../images/" + patternImage[randomNumber] + ".gif)")

Upvotes: 4

Quentin
Quentin

Reputation: 943569

You want:

"string" + variable + "string"

Not:

"string + variable + string"

Since variables in JS are not flagged using symbols (such as $ in PHP), you can't interpolate variables in strings, you have to build them with concatenation.

Upvotes: 3

Related Questions