tengo un Div que contiene una imagen con la identificación puesta de sol a la que quiero agregar un clic para cambiar su ancho de CSS 25% a 100%
no puedo ver por qué mi código no funciona
var content = document.getElementById("sunset"); var first_click = true; content.addEventListener("click", function () { if (first_click) { content.style.width = "100%"; } else { content.style.width = "25%"; } });CSS
#sunset{ width:25% }La primera instrucción if no verifica si la variable first_click es verdadera (suponiendo que eso es lo que pretende hacer). Dado que está vacío, devolvería falso y se ejecutaría la declaración else, manteniendo su imagen en un 25%.
prueba esto:
var content = document.getElementById("sunset"); var first_click = true; content.addEventListener("click", function () { if (first_click == true) { content.style.width = "100%"; } else { content.style.width = "25%"; } });¿Ha intentado agregar altura a su contenedor? Esto debería funcionar
var content = document.getElementById("sunset"); var first_click = true; content.addEventListener("click", function () { if (first_click) { content.style.width = "100%"; first_click = false; } else { content.style.width = "25%"; } }); #sunset{ width:25%; background: #000; height: 200px; } <div id="sunset"></div>El problema es que no cambia la variable first_click a true o false cuando se hace clic en la imagen. El siguiente código soluciona esto configurando first_click = !first_click :
var content = document.getElementById("sunset"); var first_click = true; content.addEventListener("click", function() { if (first_click) { content.style.width = "100%"; } else { content.style.width = "25%"; } first_click = !first_click; }); #sunset { width: 25% } <img id="sunset" src="https://dummyimage.com/150/f8f">