Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
changing a Javascript image on event listener click

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%

cannot see why my code is not working

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%
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.

try this:

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%";
    }

});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Have you tried adding height to your container ? This should work

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> 

about 4 years ago · Juan Pablo Isaza Denunciar

0

The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting 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">

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda