A
A
a16a2018-03-02 07:57:01
JavaScript
a16a, 2018-03-02 07:57:01

How to run a js script at a specific location?

Hello.
There is a counter animation script, and this script is loaded immediately when you run the page. And when you reach a certain place, the counter has already finished its work.
It is necessary to make the script start working when the screen crawls to these elements or block.

$('.count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 5555,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Kalibrov, 2018-03-02
@rework

Put the code in a function and call it on the scroll event when it reaches the element you need:

function start_count() {
    $('.count').each(function () {
        $(this).prop('Counter',0).animate({
            Counter: $(this).text()
        }, {
            duration: 5555,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
            }
        });
    });
}

$(function() {
    var oTop = $('.count').offset().top - window.innerHeight;
    $(window).scroll(function(){
        var pTop = $('body').scrollTop();
        if( pTop > oTop ){
            start_count();
        }
    });
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question