This piece is somewhat technical so if the word jQuery has no meaning to you, you might want to calmly back away from your computer or your head may explode. You've been warned!
So I ran into an interesting problem while designing one of the animations used on the FAQ page. Stated as simply as possible: I found that one must be careful about triggering animations within animations particularly when the outer animation(s) applied to an array of jQuery objects while the inner animation applied to a jQuery object completely external to the objects that are being manipulated with the outer animation. Seems straightforward enough right?
What was I doing to find this out? Great question! If you visit the FAQ page you will find an orange button titled "View all answers." This button, when clicked, triggers a series of events. The events happen as follows:
- Slide the answers open
- Add padding to the bottom of the answer for readability
- Scroll the browser window to get the Q&A in focus
So, I thought I could do this:
$faqAnswer.slideDown(500, function() {
$faqAnswer.animate({paddingBottom:'20px'}, 500, null, function(){
var cPos = $faqControls.position();
$window.animate({scrollTop: cPos.top}, 500);
});
}).addClass('open');
At first I though everything was dandy but when I tried to scroll with the mouse wheel, the screen would just bounce. So what was the problem? The problem was that for each of the answers that was being opened, a new window animation was started. This was actually a problem that was choking the browser nicely. It seemed as though the window animations were fighting with each other.
So what was the fix? The "each" function (or method) and a check to see if we were at the last answer: If so, we could animate the window afterward. The solution for me looks like this:
var nQuestions = $faqAnswer.length;
$faqAnswer.each(function(i) {
// Don't fire window movement
if (i < nQuestions - 1) {
$(this).slideDown(500, function() {
$(this).animate({paddingBottom:'20px'}, 500);
}).addClass('open');
}
// Reached the last Q! Fire window movement!
else {
$(this).slideDown(500, function() {
$(this).animate({paddingBottom:'20px'}, 500, null, function(){
var cPos = $faqControls.position();
$window.animate({scrollTop: cPos.top}, 500);
});
}).addClass('open');
}
});
In conclusion, let's a give a big round of applause to our good friend the jQuery each method! It can really be a powerful ally. I love nested animations so I figure I will be re-using this little tidbit of knowledge from time to time. I imagine this may never help anyone except me, however if it does help you get over your jQuery hiccup, Great! Glad to help. If you have questions, please drop us a comment or contact us.
Thanks!








