Firstly, an 'id' is supposed to be unique - that's not the case here. I don't know if the purpose is to let them all at once increment on hover, but if it is, you better give them a
class 'shiva' and 'talkbubble' and change your JavaScript and CSS accordingly.
Now to your actual problem: the reason why it decrements at the end.
You have this line:
Counter: $(this).text()
You're telling to count to the current text value. But what if you hover over the element while the text is
not 200? Then after the first counter, you'll start another counter that simply counts back. That's not what you want. So you can set a
data-max
attribute on every counter span that contains the value to count to:
<div id="shiva"><span class="count" data-max="200">200</span></div>
And then, rather from using .text() to get the value to count to, use
.data('max')
.
That's not all though - when I tried this out, it would only count up once, and not on all hovers. To resolve that, you can tell to animate
{ Counter: 0 }
to 200 rather than a jQuery element after setting a property. Note that, if you do this, you can't use
$(this).text
anymore, so you have to set a variable like
var counterSpan
before to replace your
$(this)
.
Additionally, you want
mouseenter
instead of
mouseover
, so you don't get tons of events when a mouse stays on the element.
Lastly, following the above steps will cause the counter to re-start when you leave and enter for a second time. That doesn't sound desirable. So at the start of the animation, you can set
.prop("animating", true)
and before that, check if
.prop("animating")
is true: if it is, you don't want to animate because an animation is already going on. When the animation is complete, you want to set the "animating" prop to false again so you can animate for a second time.
All of this combined, you get this code:
$(document).ready(function() {
$('#shiva').on('mouseenter', function() {
$('.count').each(function() {
var counterSpan = $(this);
if (counterSpan.prop('animating')) {
return;
}
counterSpan.prop('animating', true);
$({
Counter: 0
}).animate({
Counter: $(this).data('max')
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
counterSpan.text(Math.ceil(now));
},
complete: function() {
counterSpan.prop('animating', false);
}
});
});
});
});
Live demo:
on JSFiddle[
^]