I'm trying to make a button that changes the background of my HTML page. Sadly everything I've tried has not been successful, my function just doesn't do anything on click. I tried a few things that others have posted here but none of them worked.
function night() {
let element = document.body;
if (element.src.match('image/night.jfif')) {
element.src = "image/day.jpg";
console.log("day")
} else {
body.style.backgroundimage = "url('image/night.jfif')";
console.log("night")
}
}
<body style="background-image:url('image/Day.jpg')">
<button onclick="night()"> Theme </button>
</body>
CodePudding user response:
function night() {
if (currentImage === 'image1.jpg') {
document.body.style.backgroundImage = 'url("image2.jpg")';
currentImage = 'image2.jpg';
} else {
document.body.style.backgroundImage = 'url("image1.jpg")';
currentImage = 'image1.jpg';
}
}
Try this. It might help
CodePudding user response:
This'll do it.
var backimg = 0;
function night(){
backimg = 1-backimg;
let b = 'image/Day.jpg';
if (backimg == 1){
b = 'image/night.jfif';
}
document.body.style.backgroundImage = "url('" b "')";
}
<body style="background-image:url('image/Day.jpg')">
<button onclick="night()"> Theme </button>
</body>