Krystian
Krystian

Reputation: 987

Start functions when bootstrap carousel-selector has class selected

The following functions shows counting numbers. Its within a bootstrap carousel.

I want to start this function, when the bootstrap carousel-selector has class="selected" and not immediately on pageload.

AND 2nd condition should be that the user really is on that part of page (#video). So the function does not start when he does not see the function related part (maybe via scrollspy somehow?). How can I do this?

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

Question is regarding this page (last slide): https://bm-translations.de/km#video

enter image description here

Upvotes: 2

Views: 139

Answers (1)

Rence
Rence

Reputation: 2950

First condition:
Check if Carousell has Class

if $('#yourcaroussellID').hasClass('selected')

Second condition
Compare users position on page to the elements position on page

isInViewport = function() {
    var videoTop = $('#carouselMarketing1').offset().top;
    var videoBottom = videoTop + $('#carouselMarketing1').outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return videoBottom > viewportTop && videoTop < viewportBottom;
}

You will need to check the combined ifs at an interval to see the changes in scrolling:

myInterval = setInterval(function(){ 
    if ($('#carousel-selector-4').hasClass('selected') && (isInViewport())) { 
        yourCounter();
        myStopFunction();
    }
}, 1000);

Make your counter a function you can call:

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

Make a stop function for the interval:

function myStopFunction() {
    clearInterval(myInterval );
}

Upvotes: 2

Related Questions