Search code examples
javascriptjqueryappendtodetach

jquery appendTo and detach in order to replay animated gif


This is my js:

$(document).ready(function () {
    $lrgBanner = $('#panel');
    $lrgBanner.detach();

    $('#banner img').click(function () {
        $lrgBanner.appendTo('#ad').show();
        $('#banner').hide();
        console.log('banner was clicked');
    });

});

$('#close img').click(function () {
    $('#banner').show();
    $lrgBanner.detach();
    console.log('close was clicked');
});

And the HTML:

 <div id='ad'>

    <div id='banner'>
        <img src="img/hp-small.gif" alt="banner advertisement" />
    </div>

    <div id='panel'>
        <div id='background'>
            <img src="img/hp-large.gif" alt="" />
        </div>
        <div id='close'>
            <img src="img/btn_close.gif" alt="close" />
        </div>
    </div>

</div>

The div #background contains an animated gif. I was told that using detach and appendTo would restart the gif content, but it doesn't seem to be working.

I wondered about trying to use a load function (or an unload on the #close img click function.

Does anyone have any advice?

Thanks in advance.


Solution

  • You should reset src attribute of animated gif instead:

    SEE DEMO

    Note that you shouldn't set variables as global if you don't need to access it from global scope.

    $(document).ready(function () {
         gifAnimated = $('#background img')[0],
         gifSrc = "http://mlkshk.com/r/R245.gif";
         $lrgBanner = $('#panel');
         $lrgBanner.detach();
    
         $('#banner img').click(function () {
             gifAnimated.src = gifSrc;
             $lrgBanner.appendTo('#ad').show();
             $('#banner').hide();
             console.log('banner was clicked');
         });
    
     });
    
     $('#close img').click(function () {
         $('#banner').show();
         $lrgBanner.detach();
         gifAnimated.src = "";
         console.log('close was clicked');
     });