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

134
Visualizações
Javascript function continues a step longer than needed

I have a function that continues one step longer than needed. When the image (elefant.png) is clicked the image (scale1.png) is changed. There are 5 pictures and it works fine. Problem is that when the last picture is displayed, and I click (elefant.png) again it comes to an undefined picture? I don't understand why it doesn't just stop on the last picture (scale5.png)?

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <link rel="stylesheet" href="style.css">
  <body>

    <div class="wrapper1">

      <h2 id="title_text">Hey</h2>

        <img src="image/scale1.png" id="getImage">

        <img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">



    </div>

    <script type="text/javascript">

        var counter = 0,
    gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
    imagefun = function () {
        document.getElementById("getImage").src = gallery[counter];
        counter++;
        if (counter >= 4) {
            document.getElementById("title_text").innerHTML = "New text!";
        }

    };

    </script>


  </body>
</html>

This might be an easy fix, but I am not good with javascript. I tried searching for an answer but I'm not sure what to even look for as I don't know what causes the issue?

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

0

I'm not exactly sure what your end result should be once you hit the end of your gallery array but as it stands it changes title_text to "New text!".

The problem with your code as it stands is you always increment counter and change the source getImage based on that integer. That doesn't stop once your counter hits 4.

I'd use the array length as a stopping point and only increment the counter variable up until that limit is hit. I would write something like this:

var counter = 0,
gallery = ["image/scale2.png", "image/scale3.png", "image/scale4.png", "image/scale5.png"],
imagefun = function () {
  if (counter >= gallery.length) {
      document.getElementById("title_text").innerHTML = "New text!";
  }
  else{
      document.getElementById("getImage").src = gallery[counter];
      counter++;
  }
};
<div class="wrapper1">
  <h2 id="title_text">Hey</h2>
  <img src="image/scale1.png" id="getImage">
  <img src="image/elefant.png" style="width:250px; height:auto;" onclick="imagefun()">
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You always run the function and change the image source, and only then check for counter's value. That's why it'll keep going and changing the source even when counter is bigger than 3.

A solution would be to change counter' s value conditionally:

if (counter < gallery.length - 1) {
  counter++;
} 
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