简体   繁体   中英

Call function at scroll once

I have jQuery function counter and I need to call it when I scroll page

$(document).ready(function () {

    $.fn.counter = function () {
        $(this).each(function () {
            var num = $(this).data('counter');
            var i = 1,
                self = $(this).html(i);
            var interval = setInterval(function () {
                self.html(++i);
                if (i >= num) {
                    clearInterval(interval);
                }
            }, 100);
        });
    };

    $(window).scroll(function() {
        var height = $(window).scrollTop();

        if(height  > 300) {
            $('.counter-1, .counter-2, .counter-3, .counter-4').counter();
        }
    });

});

The problem is when I scroll page again up or down function is called again and again every time.

I tried to use this code

$(document).ready(function () {

    $.fn.counter = function () {
        $(this).each(function () {
            var num = $(this).data('counter');
            var i = 1,
                self = $(this).html(i);
            var interval = setInterval(function () {
                self.html(++i);
                if (i >= num) {
                    clearInterval(interval);
                }
            }, 100);
        });
    };

    $(window).one('scroll', function () {
        var height = $(window).scrollTop();

        if (height > 300) {
            $('.counter-1, .counter-2, .counter-3, .counter-4').counter();
        }
    });

});

but in this case after the reloading the page function is not called.

Is there any way to call function only once on scroll and don't call it again but call it after the reloading the page ?

You should use a name space with .on/.off :

$(window).on('scroll.custom', function () {
    var height = $(window).scrollTop();

    if (height > 300) {
        $('.counter-1, .counter-2, .counter-3, .counter-4').counter();
        $(window).off('scroll.custom')
    }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM