Search code examples
javascriptimagewysiwyg

Javascript - Change image after some amount of time


This may be a common question, but I have tried some solutions, and my code isn't work yet.

So, I have a .GIF image on my WYSIWYG page. My code works fine to start and to replay my .gif, by changing an ImageStart.jpg to my Image.gif. But i need to load a new image "ImageEnd.jpg after my Image.gif has ended.

So, I've tried SetTimeout:

function play(){
  if (document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaStart.jpg"){
    document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa.gif";
  }else{
    document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa1.gif"; 
  }
  SetTimeout(function(){end()},24000);
}

function end(){
  document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaEnd.jpg";
}

The way I see it, my code should change my Image.gif to an ImageEnd.jpg after 24 seconds, which is the lenght of the animation.

Something wrong about it?


Solution

  • The logic in your if condition is faulty in addition to the setTimeout misspelling. Should use two equal signs to perform a comparison. Also, try to store a reference to a DOM element instead of searching for it every time. Also makes for cleaner code.

    function play(){
      var img = document.getElementById("Pesquisa");
      if (img.src == "http://www.lyuz.com.br/media/./images/Software/PesquisaStart.jpg"){
        img.src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa.gif";
      }else{
        img.src = "http://www.lyuz.com.br/media/./images/Software/Pesquisa1.gif"; 
      }
      setTimeout(function(){end()},24000);//you had SetTimeout(...), upperCased S previously
    }
    
    function end(){
      document.getElementById("Pesquisa").src = "http://www.lyuz.com.br/media/./images/Software/PesquisaEnd.jpg";
    }