This is my code: Fiddle
countEach() $(window).on('scroll', function(e) { countEach() }) function countEach() { $('.count').each(function() { if (showOnScreen(this) && $(this).attr('show') != 'false') { console.log($(this).text()) console.log($(this).attr('show')) $(this).attr('show', 'false') numberAnimate(this) } else if (!showOnScreen(this)) { $(this).attr('show', 'true') } }) } function showOnScreen(target) { if ($(window).scrollTop() + $(window).height() >= $(target).offset().top) return true; else return false; } function numberAnimate(target) { var $this = $(target); jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, { duration: 1000, easing: 'swing', step: function() { $this.text(this.Counter.toFixed(1)); } }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="count">5.6</span> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <p>Scroll up and then scroll down again</p> <span class="count">5.6</span>
The problem is, the increasing number animation will run again, if i scroll up and scroll down again. What is the thing that i need to change to stop it? I tried a lot of things, but i am not good at Javascript.
Use a global variable. Set it to false
at the beginning. In the scroll event, check it and if it is still false
, run the countEach()
function then change the variable to true
. Like this:
var stop = false;
countEach();
$(window).on('scroll', function(e) {
if(!stop){
countEach();
stop = true;
}
})
You need to declare a global var as stopNow = 2
so your animation can only run twice and decrement it when animation runs.
var stopNow = 2;
Update the countEach function as follows
function countEach() {
$('.count').each(function() {
//also check stopNow != 0
if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
console.log($(this).text())
console.log($(this).attr('show'))
$(this).attr('show', 'false')
numberAnimate(this)
stopNow = stopNow - 1; //decrement stopNow
} else if (!showOnScreen(this)) {
$(this).attr('show', 'true')
}
})
}
Here's your updated working fiddle - https://jsfiddle.net/6w8ubh5y/7/
Change the event binding code from:
$(window).on('scroll', function(e) {
countEach()
})
to
$(window).on('scroll', countEach);
and change countEach function like this...
function countEach() {
$('.count').each(function() {
...
});
$(window).off('scroll', countEach); // add this line
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.