I’m having a very specific problem, I don’t even know what to look for in Google…
I’m trying to create an animated letter. There’s a pen and 5 lines which are in a separate tag, all within one container element, positioned relatively, having their own ID, and the lines are hidden (all on their place, where they should appear). The animation is like this: the pen moves diagonally, a line appears, the pen moves to the beginning of the new line, repeat 5 times, pen goes back to default position, lines disappear.
I didn’t want to write the animation code for all 5 cycles separately, so I inserted the animations into a queue using a for cycle. Everything is working fine, except the silliest thing – I can’t get the current line number to show. Here’s the code:
var penAnimating = false;
function animateLetter() {
var pen = $('#form_decor_pen');
var startRight = pen.css('right');
var startTop = pen.css('top');
if (!penAnimating) {
penAnimating = true;
for (var i=1; i<=5; i++) {
pen.animate( {
right: '-=26',
top: '-=10',
},{
duration: 600,
queue: 'penAnimation'
});
Here’ the problem part:
pen.queue('penAnimation', function(next) {
//var line = $('#form_header_decor :nth-child(' + i.toString() + ')')
var line = $('#line_' + i.toString())
line.show();
//alert(line.id);
next();
})
The problem is, i always outputs 5 – the number at which the cycle ends.
if (i<5) {
pen.animate({
right: '+=26',
top: '+=20',
},{
duration: 300,
queue: 'penAnimation'
});
} else {
pen.animate({
right: startRight,
top: startTop,
},{
duration: 300,
queue: 'penAnimation',
complete: function() {
penAnimating = false;
}
});
}
}
pen.dequeue('penAnimation');
}
}
When you have a for loop that has asynchronous calls in it the value of the for variable is going to be the last value. Unless you put the code in a closure.
Change the for loop to a for-loop-with-a-closure.