FreeTheStudents
FreeTheStudents

Reputation: 171

Refreshing Animated Gif on Button Click

I have been stuck on this problem for a while now and I need some help trying to figure out how to "refresh" a gif image every time I hit a button. I have tried a ton of the online ideas for this but none of them seem to be working. It only will play the gif once I clear my browser history so I think it may be some caching problem. Can someone spot where I am going wrong or have any tips on how to fix this?

My html:

    <div class="logo">
        <button class="chains" id="chains" onclick="chains();"></button>
            <div id="png">
                <img src="images/logo.png" alt=""/>
            </div>
            <div id="gif">
                <img src="images/chains.gif" alt="" />
            </div>
    </div>

My Javascript function:

    <script language="JavaScript">
    $( document ).ready(function() {
        var myDiv = document.getElementById('gif');
        myDiv.style.visibility = "hidden";
    });

    function chains() {
            d = new Date();
            $("#gif").attr("src", "images/chains.gif?"+d.getTime());
            var logo = document.getElementById("png");
            var gif = document.getElementById("gif");

            var hide = function(){
              logo.style.visibility = "hidden";
              gif.style.visibility = "visible";
              setTimeout(show, 2300);  // 5 seconds
            }

            var show = function(){
              gif.style.visibility = "hidden";
              logo.style.visibility = "visible";
            }

            hide();
    };
</script>

Upvotes: 1

Views: 2561

Answers (1)

Tommy
Tommy

Reputation: 850

I hope I found the answer here!

Let me quote:

in a nut shell load the image into a javascript variable then change out the src on click

$(function(){
  var image = new Image();
  image.src='http://rack.3.mshcdn.com/media/ZgkyMDEyLzEwLzE5LzExXzMzXzMzXzE3Nl9maWxlCnAJdGh1bWIJMTIwMHg5NjAwPg/462b8072';
   $('#img').click(function(){
     $(this).attr('src',image.src);
   }); 
 });

EDITED: https://jsfiddle.net/op3t82ea/2/

Made some changes and enhancements and added comments in the code! Hope this helps :)

Upvotes: 1

Related Questions