var foo = $("div").bind("click", function() {
$("div").animate({"height" : "500px"}, 2000);
$("div").animate({"height" : "50px"}, 2000);
$("div").unbind();
});
Asked
Active
Viewed 841 times
2
-
Do you mean, `$(this).unbind("click");` ? I Don't understand what you're after. – karim79 Jun 01 '11 at 08:16
2 Answers
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);

Felix Kling
- 795,719
- 175
- 1,089
- 1,143
-
2
-
@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