function myFunction() {
var element = document.body;
element.classList.toggle("light-mode");
var btndrk = document.getElementById('drk');
if (btndrk.style.backgroundImage === "url('https://assets.codepen.io/1462889/moon.svg')") {
onlick(btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/sun.svg')");
} else {
btndrk.style.backgroundImage = "url('https://assets.codepen.io/1462889/moon.svg')";
}
}
#drk {
position: relative;
height: 70%;
width: 3.3%;
top: 15%;
background-color: rgb(105, 50, 255);
color: white;
font-family: 'Advent Pro', sans-serif;
border-radius: 5px;
background-image: url('https://assets.codepen.io/1462889/moon.svg');
background-size: 45% 45%;
background-repeat: no-repeat;
background-position: center;
border-radius: 50%;
border: none;
transition: all 200ms linear;
box-shadow: 0 0 1vw rgba(255,235,167,.25);
}
<button id="drk" onclick="myFunction()"></button>
I want to have the original background image come back on the second click and the sun.SVG show on the third and so-on and so-fourth. Right now the original background-image shows when I refresh the page but after one click it changes to sun.SVG and does not change back. I want it to toggle between the two.
CodePudding user response:
You don't need to do the image change in JS.
The JS can simply be:
document.getElementById('drk').addEventListener("click", function() {
document.body.classList.toggle("light-mode");
});
And for the CSS part you need to add:
body.light-mode #drk {
background-image: url('https://assets.codepen.io/1462889/moon.svg');
}
body:not(.light-mode) #drk {
background-image: url('https://assets.codepen.io/1462889/sun.svg');
}
document.getElementById('drk').addEventListener("click", function() {
document.body.classList.toggle("light-mode");
});
html,body{height:100px;}
#drk {
position: relative;
height: 70%;
width: 3.3%;
top: 15%;
background-color: rgb(105, 50, 255);
color: white;
font-family: 'Advent Pro', sans-serif;
border-radius: 5px;
background-image: url('https://assets.codepen.io/1462889/sun.svg');
background-size: 45% 45%;
background-repeat: no-repeat;
background-position: center;
border-radius: 50%;
border: none;
transition: all 200ms linear;
box-shadow: 0 0 1vw rgba(255,235,167,.25);
}
body:not(.light-mode) {
background: #555;
}
body.light-mode #drk {
background-image: url('https://assets.codepen.io/1462889/moon.svg');
}
<button id="drk"></button>