jQuery: Counter, Tricky problem with effects for brainy people
I made this counter that I think is cool because it only makes visible changes to the numbers being changed between each time it is triggered.
This is the code
// counter
$('a').click(function(){
var u = '';
var newStr = '';
$('.counter').each(function(){
var len = $(this).children('span').length;
$(this).children('span').each(function(){
u = u + $(this).text();
});
v = parseInt(u) + 1;
v = v + '';
for (i=v.length - 1; i >= 0; i--) {
if (v.charAt(i) == u.charAt(i)) {
break;
}
}
slce = len - (v.length - (i + 1))
updates = $(this).children('span').slice(slce);
$(updates).fadeTo(100,0).delay(100).each(function(index){
f = i + 1 + index;
$(this).text(v.charAt(f));
}).fadeTo(100,1);
});
});
Markup:
<span class="counter">
<span></span><span></span><span></span><span></span><span></span><span></span><span style="margin-right:4px;">9</span><span>9</span><span>9</span><span>9</span>
</span>
<a href="">Add + 1</a>
The problem is that I previously used queue() function to delay() $(this).text(v.charAt(f)); by 100ms, (without queue the text()-function would not be delayed because it isnt in the fx catergory) so that the text would be updated before the object had faded to opacity = 0. That would look stupid.
When adding multiple counters, only one of the counters would count. When removing the queue function, both counters would work, but as you can imagine, the delay of the text() would be gone (as it isnt fx-category).
It is probably a bit tricky to make out how I开发者_开发问答 can have multiple counters, and still delay the text()-function by 100ms, but I was hoping there is somebody here with spare brain capacity for these things ;)
You can see a (NSFW) problem demo here:
Just look underneath the sharing icons and you will notice that the text changes WHILE the objects fade out.
Looking for some help to sove this problem. I would like to call the text() function once the text has faded to opacity 0, then fade in once the text() has executed.
Thank you for your time.
As 'omfgroflmao' said in the comments, effects have callbacks:
$(updates).fadeOut(100, function() {
f = i + 1 + index;
$(this).text(v.charAt(f));
$(this).fadeIn(100);
});
See for instance the fadeOut docs
Edit: In your example, it might also be cleaner to store the counter using .data()
rather than building it from the span elements.
// init counter
$('.counter').data('tally', 0);
// when you're incrementing
var u = $(this).data('tally') + '';
$(this).data('tally', $(this).data('tally') + 1);
var v = $(this).data('tally') + '';
// work out which span elements to update etc
精彩评论