Fire event after scrolling to a specific div or id
I've searched a lot these days but i didn't manage to solve my problem.
I have the script below which is a simple counter, that counts some stats starting from 0. It starts when my page loads. I would like to fire this event when i scroll to a specific div or id, but only once. I saw a lot examples with .one() method etc. but i didn't find out the proper solution.
Here is my script.
<script type="text/javascript">
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,
end: 100,
easing: 'swing',
duration: 500,
complete: ''
}, options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end}, {
duration: settings.duration,
easing: settings.easing,
step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},
complete: settings.complete
});
};
$('.number1').jQuerySimpleCounter({end: 14,duration: 2899});
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300});
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000});
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500});
</script>
So what should i add to trigger it after reaching a certain div or id...?
I managed to find a "good" solution that works for me. doing the below "not so good" thing. :) Thanks Nikolas for your help.
<script type="text/javascript">
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var one = $('.tworow').position().top;
var two = $('.endrow').position().top;
if (scroll > one & scroll < two) {
$.fn.jQuerySimpleCounter = function( options ) {
var settings = $.extend({
start: 0,
end: 100,
easing: 'swing',
duration: 500,
complete: ''
}, options );
var thisElement = $(this);
$({count: settings.start}).animate({count: settings.end}, {
duration: settings.duration,
easing: settings.easing,
step: function() {
var mathCount = Math.ceil(this.count);
thisElement.text(mathCount);
},
complete: settings.complete
});
};
$('.number1').jQuerySimpleCounter({end: 14,duration: 2899});
$('.number2').jQuerySimpleCounter({end: 350,duration: 3300});
$('.number3').jQuerySimpleCounter({end: 450,duration: 4000});
$('.number4').jQuerySimpleCounter({end: 7,duration: 2500});
};
});
When the scroll reaches a certain div it starts, and after that i put another div where the event should end, controlling it with an if condition. Now the area of the page that triggers the event is a very small "area" between 2 divs.
这应该会给你你想要的结果:
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
var one = $('element').position().top;
var count = 0;
if (scroll > one) {
var newCount = count + 1;
if (newCount === 1) {
//do something
};
};
});
链接地址: http://www.djcxy.com/p/83398.html
上一篇: 如何阅读jQuery中的绑定悬停回调函数
下一篇: 滚动到特定的div或id后触发事件