tags:

views:

142

answers:

3

I'm using the following code to animate a div. When the animation finishes I would like to remove it.

<script>
$(function() {
  $("a.shift").click(function() {
   $("#introOverlay").animate({
   height: 0,
   }, 2000)
   });

  });
</script>

Any help?

Thanks

A: 

Use window.timeout with the same amount of time as taken by the animation.

Jeff Ober
+2  A: 

JQuery animate(params, [duration], [easing], [callback] ) offers the possibility to add a callback that is called for every time the animation is completed

callback (Optional) Function: A function to be executed whenever the animation completes, executes once for each element animated against.

The syntax is pretty much jQuery straightforward:

<script>
$(function() {
    $("a.shift").click(function() {
     $("#introOverlay").animate({
     height: 0,
     }, 2000, "linear",
      function() {
       $("#introOverlay").hide();
      }
     )
     });

    })
</script>

See also this SO question

Daff
Thanks Daff,Can you give me some sample code? It's the syntax I don't understand.
Martin
Check out the question I linked, there is a code sample there (copied it here, too). Basically you just pass the callback function as a parameter.
Daff
+1  A: 

animate takes 2 more params, so you could do:

$("a.shift")
    .click(function() 
        {
            $("#introOverlay")
                .animate({height: 0}, 2000,"linear",function()
                    {
                        $(this).remove();
                    }
                )
        }
    );

Untested.

EDIT: Tested: here's the full page I used, which expands to 300px make removal more obvious:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
 <head>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
  <script type="text/javascript">
   //<![CDATA[
   $(document).ready(function()
   {
    $(".shift").click(function() 
    {
     $("#introOverlay")
     .animate({height: 300}, 2000,"linear",function()
     {
      $(this).remove();
     })
    });
   });
   //]]>
  </script>
 </head>
 <body>
 <a class="shift" href="javascript:void(0)">clickme</a>
 <div id="introOverlay" style="background-color:red;height:200px;">overlay</div>
 </body>
</html>
spender
Hi Spender,That doesn't remove the element when animation has finished.
Martin
Perfect! Thanks!
Martin