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>Quiero que la imagen de fondo original vuelva con el segundo clic y que se muestre sun.SVG con el tercero y así sucesivamente. En este momento, la imagen de fondo original se muestra cuando actualizo la página, pero después de un clic cambia a sun.SVG y no vuelve a cambiar. Quiero que cambie entre los dos.
No necesita hacer el cambio de imagen en JS.
El JS puede ser simplemente:
document.getElementById('drk').addEventListener("click", function() { document.body.classList.toggle("light-mode"); });Y para la parte CSS necesitas agregar:
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>