Search code examples
javascripthtmlsrc

How to I make the image switch back to the original image src after Iv'e pressed the button once


<html>
<body>

<button onclick="document.getElementById('myImage').src='hagthrowingball.gif'">Throw Fire ball</button>

<img id="myImage" src="foresthag.gif" style="width:100px">


</body>
</html>

I need the image src onclick to show the image hagthrowingball.gif, but then go back to foresthag.gif without pressing the button again.


Solution

  • I think this should solve your problem by automaticly setting back old src after some time;

    <button onclick="replaceFunc();">Throw Fire ball</button>
    
    <img id="myImage" src="foresthag.gif" style="width:100px">
    
    <script>
      function replaceFunc (){
          const el = document.getElementById("myImage");
          const oldSrc = el.src;
          el.src = 'hagthrowingball.gif';
          setTimeout(()=>el.src=oldSrc, 1000);
      }
    </script>
    </body>
    </html>