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

196
Visualizações
How does changing an image src when the user clicks on it work?

I'm trying to create a simple code where if the user clicks on the gif, it'll switch to another gif repeatedly until it reaches the end of the loop, where the loop restarts. This is the relevant chunk of code:

var storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
var onGifClick = function(){
    if (document.getElementById("coloredGif").src === "/images/green.gif"){
        document.getElementById("coloredGif").src = "/images/blue.gif";

    } else if (document.getElementById("coloredGif").src == "/images/blue.gif"){
        document.getElementById("coloredGif").src = "/images/yellow.gif";

    } else if (document.getElementById("coloredGif").src == "/images/yellow.gif"){
        document.getElementById("coloredGif").src = "/images/red.gif";

    } else if (document.getElementById("coloredGif").src == "/images/red.gif"){
        document.getElementById("coloredGif").src = "/images/green.gif";
    }}
storedColoredGif.addEventListener("click", onGifClick);

It's very straightfoward. All of the path names are correct and the gifs source is initially green. The program stores the gif in a variable, then in the function it checks for what the source of the gif is and changes it accordingly when the user clicks on the gif. But nothing happens when I click on it. Am I doing something wrong in my loops? If I had to guess, the problem is that I am correctly changing the source, its just that im never updating the html (but refreshing the page would set the gif to green again because thats what i set in the main html body). What am I doing wrong?

This is how the gif is put in the html (the green.gif is shown fine, its just that its not switching between the gifs when clicked)

    <img src="/images/green.gif" id="coloredGif" title="Click me!">

FINAL EDIT: thanks to 2 very helpful users below I was able to figure out that getting the src of the gif actually returns the full domain path, and as such my if statements never progress because theyre always false. Both of their solutions worked.

The solution was to simply work around the fact that checking the src returned the full domain path, instead of just the folders and gif path

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

The .src will returns a full string of the path: http://example.com/img/... instead of just what you're comparing in your if statement.

Here is a console.log of both .src and .getAttribute output for you to understand:

http://localhost:5501/images/green.gif // Output of .src
/images/green.gif // Output of getAttribute

It should be clearer now about why your if statement wasn't working: you were checking for something that was simply false in all cases. Do not hesitate to console.log values that you're checking when you run into those problems, it, in most of the case, will clear the situation.

Instead, my advice is to uses the .setAttribute to set it, and .getAttribute to get it, which returns the correct path that you're searching for.

Also, you may consider using let & const rather than var. Here is the code using both methods as stated above.

const storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif

storedColoredGif.addEventListener("click", () => {
    const currentColoredGif = document.getElementById("coloredGif").getAttribute("src")
    if (currentColoredGif == "/images/green.gif") {
        storedColoredGif.setAttribute("src", "/images/blue.gif")
    } else if (currentColoredGif == "/images/blue.gif") {
        storedColoredGif.setAttribute("src", "/images/yellow.gif")
    } else if (currentColoredGif == "/images/yellow.gif") {
        storedColoredGif.setAttribute("src", "/images/red.gif")
    } else if (currentColoredGif == "/images/red.gif") {
        storedColoredGif.setAttribute("src", "/images/green.gif")
    }
})
about 4 years ago · Juan Pablo Isaza Relatório

0

img src includes the domain as well, for simplicity just check includes, which executes if the string is included in the src

How includes method works - MDN ref

var storedColoredGif = document.getElementById("coloredGif"); //we grab the gif and store it in storedColoredGif
var onGifClick = function() {

  if (document.getElementById("coloredGif").src.includes("/images/green.gif")) {
    document.getElementById("coloredGif").src = "/images/blue.gif";

  } else if (document.getElementById("coloredGif").src.includes("/images/blue.gif")) {
    document.getElementById("coloredGif").src = "/images/yellow.gif";

  } else if (document.getElementById("coloredGif").src.includes("/images/yellow.gif")) {
    document.getElementById("coloredGif").src = "/images/red.gif";

  } else if (document.getElementById("coloredGif").src.includes("/images/red.gif")) {
    document.getElementById("coloredGif").src = "/images/green.gif";
  }
}
storedColoredGif.addEventListener("click", onGifClick);
<img src="/images/green.gif" id="coloredGif" title="Click me!">

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