2

http://jsfiddle.net/3NRsd/

var foo =  $("div").bind("click", function() {
    $("div").animate({"height" : "500px"}, 2000);
    $("div").animate({"height" : "50px"}, 2000);
    $("div").unbind();
    });
Reporter
  • 3,897
  • 5
  • 33
  • 47
l2aelba
  • 21,591
  • 22
  • 102
  • 138

2 Answers2

3

You could do:

function handler() {
    $(this)
     .unbind()
     .animate({"height" : "500px"}, 2000);
     .animate({"height" : "50px"}, 2000, function(){
         $(this).click(handler); // <- gets called once the animation finishes
     });
}

$('div').click(handler);

DEMO

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 2
    Pleeeeease cache `$(this)`, or even better, do it on a chain. ;) – DarthJDG Jun 01 '11 at 08:17
  • @DarthJDG - Can you explain what your comment means or post a link... :) – El Ronnoco Jun 01 '11 at 08:19
  • 2
    @DarthJDG: Right, chaining is better. Regarding caching `this`: Yes, it is an overhead but a small one and there are not too many calls in this function to jQuery. And besides that, performance optimization should be done after the code works ;) – Felix Kling Jun 01 '11 at 08:21
  • 1
    @El Ronnoco: If you have a look at the code in the answer now, that's exactly what I meant by chaining jQuery methods. Previously there were multiple `$(this).method()` calls, which would create a separate jQuery object from `this` 3 times, which is unnecessary. – DarthJDG Jun 01 '11 at 08:22
  • 2
    @ElRonnoco: Every function call introduces some overhead. `$(this)` basically calls jQuery every time and returns a new jQuery object. While this might have some impact if you call it every often, calling it a couple of times should be fine. You can see what jQuery is doing when it is passed a DOM element (https://github.com/jquery/jquery/blob/master/src/core.js#L92) and it is not that much. It **is** better to cache it (or chaining) in terms of coding style (just looks cleaner) but certainly not because of performance. – Felix Kling Jun 01 '11 at 08:24
  • @I2aelba: your code is unformated and it is not clear what you want. Everything that should be run after the animation has to go in the callback. – Felix Kling Jun 01 '11 at 08:30
2

You can rebind it in a callback from the animate function:

http://jsfiddle.net/3NRsd/8/

Richard Dalton
  • 35,513
  • 6
  • 73
  • 91