Estoy tratando de cambiar el fondo del cuerpo en mi documento HTML usando algunas funciones básicas de JS. Configuré la función para apuntar a una ID específica, y luego la etiqueta style.background, si es la imagen de fondo actual, luego la configuré en otra que especifiqué, de lo contrario mantengo la misma imagen. He intentado cambiar el código innumerables veces, pero parece que todavía no puedo cambiar el fondo. Cualquier ayuda con esto sería apreciada.
HTML:
<div class="bg-image" style="background-image: url('./img/frankie.jpg'); height: 100vh" id="bacgr"> <!--SETS BACKGROUND using id tag to change w/ JS--> <main role="main" class="container d-flex justify-content-center"> <div class="starter-template"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p> </div> </main> </div>JS:
let myImage = document.getElementById('bacgr').style.backgroundImage; //have to target specific image(like an array ([0])), put inside div w/ id. myImage.onclick = function() { if(myImage === "url('./img/frankie.jpg')") { myImage == "url('./img/jesus_mobile.jpg')"; } else { myImage == "url('./img/frankie.jpg')"; } }Prueba esto:
const el = document.getElementById('bacgr'); el.onclick = function() { if(this.style.backgroundImage === "url('./img/frankie.jpg')") { this.style.backgroundImage = "url('./img/jesus_mobile.jpg')"; } else { this.style.backgroundImage = "url('./img/frankie.jpg')"; } }Aquí está el ejemplo
Estás cambiando solo la URL, pero eso no se volverá a asignar al elemento dom.
const el = document.getElementById('bacgr'); let prev = 'url("https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa")'; el.onclick = function() { el.style.backgroundImage = prev === el.style.backgroundImage ? 'url("https://images.unsplash.com/photo-1583508915901-b5f84c1dcde1")' : prev; } <div class="bg-image" style="background-image: url('https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa'); height: 100vh" id="bacgr"> <main role="main" class="container d-flex justify-content-center"> <div class="starter-template"> <h1>Bootstrap starter template</h1> <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p> </div> </main> </div>