Reputation: 81
I have a problem with a recurrent animation that i need to insert inside a web page.
I use an animation to show a number progression on the web page. I need just a call to this animation function each time I go hover the section but the code below behave in a strange manner. The animation is executed correctly for the first time but after the animation end it performs a sort of rollback, executing the animation in the opposite way returning to value 1.
The code I use is reported below:
$("#numberFarm").hover(function() {
$('.countIncrement .count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 3000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="numberFarm">
<div class="container">
<h2>i nostri numeri</h2>
<div class="row">
<div class="col-xs-4">
<div class="box_icon"><img src="/assets/images/transport_icon.png" /></div>
<div class="divCountIncrement">
<h4 class="countIncrement"><span class="count">38</span> <br/><span class="numberDesc">veicoli</h4></div></div>
<div class="col-xs-4"> <div class="box_icon"><img src="/assets/images/persons_icon.png" /></div> <div class="divCountIncrement"><h4 class="countIncrement"><span class="count">43</span> <br/><span class="numberDesc">staff</span></h4>
</div>
</div>
<div class="col-xs-4">
<div class="box_icon"><img src="/assets/images/kilo_icon.png" /></div>
<div class="divCountIncrement">
<h4 class="countIncrement"><span class="count">2</span> <br/><span class="numberDesc">milioni di km percorsi</span></h4>
</div>
</div>
</div>
</div>
</section>
Do you have any explanation for this strange behavior?
How can I solve this problem to prevent the return to the original condition?
Upvotes: 1
Views: 77
Reputation: 4462
Because the $("#numberFarm").hover(function () {
needs a another function()
$( the-element ).hover(
function() {
//this is the `mouseenter`
}, function() {
//this is the `mouseleave`
}
);
The .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.
Calling
$( selector ).hover( handlerIn, handlerOut )
is shorthand for:$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );
Read the documentation of .hover()
Upvotes: 4