Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda