Nevershow2016 Nevershow2016 - 7 months ago 20
HTML Question

Change background with button

I am trying to make it so that when the user clicks on a restyle button it will change the background to the images stored in my folder. I have a couple, and then you can choose to reset back to the normal image, however for some reason I cant get it to work, any help would be great on this matter:

HTML buttons

<a href="#" onclick="changeLook()">ReStyle</a>
<a href="#" onclick="changeBack()">Reset</a>


Javascript

var counter = 0;
function changeLook(){
counter += 1;
switch (counter) {
case 1:
document.body.style.backgroundImage = "../Image/BackgroundImage2.jpg";
break;
case 2:
document.body.style.backgroundImage = "../Image/BackgroundImage3.jpg";
break;
case 3:
counter = 0;
document.body.style.backgroundImage = "../Image/BackgroundImage4.jpg";
break;
}
}

function changeBack(){
document.body.style.backgroundImage = "../Image/BackgroundImage1.jpg";
}


CSS

body {
padding-top: 23px;
padding-bottom: 10px;
background: url('../Image/BackgroundImage1.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

Answer

Just add url(image path) like:

document.body.style.backgroundImage = "url(../Image/BackgroundImage2.jpg)";

var counter =0; 
function changeLook() {
    counter += 1;

    switch (counter) {
        case 1:
            document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
            break;
        case 2:
            document.body.style.backgroundImage = "url(http://placehold.it/300x300)";
            break;
        case 3:
            counter = 0;
            document.body.style.backgroundImage = "url(http://placehold.it/400x400)";
            break;          
    }
}

function changeBack(){
    document.body.style.backgroundImage = "url(http://placehold.it/200x200)";
}
body {
    padding-top: 23px;
    padding-bottom: 10px;
    background: url('http://placehold.it/200x200') no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
<a href="#" onclick="changeLook()">ReStyle</a>
<a href="#" onclick="changeBack()">Reset</a>