Cristiano Matos
Cristiano Matos

Reputation: 329

Animation continues after once trigged by scroll

I made a bar chart only with CSS and a animation from low to up that works well, however I want to run only when trigged by scroll. Somehow the animation after trigged by the scroll does not stop, it keeps running. look in the inspect element the latest bar.

jquery

// Bar Chart Animation
    function barChart(){
      $("#demographicsBars li .bar").each( function( key, bar ) {
        var percentage = $(this).data('percentage');

        $(this).animate({
          'height' : percentage + '%'
        }, 1000, function() {
            $('.viewerDemographics #demographicsBars li .bar').css('overflow','inherit');
         });
      });
    };

// Scroll Call Animation

    $(window).scroll(function () {
        $('.viewerDemographics').each(function () {
            var imagePos = $(this).offset().top;
            var imageHeight = $(this).height();
            var topOfWindow = $(window).scrollTop();

            if (imagePos < topOfWindow + imageHeight && imagePos + imageHeight > topOfWindow) {

                barChart();

            } else {


            }
        });
    });

jsfiddle

Upvotes: 0

Views: 30

Answers (1)

Popnoodles
Popnoodles

Reputation: 28419

It's because you're asking it to.

http://jsfiddle.net/g6r1vngh/1/

Tell JS it hasn't been drawn

// Bar Chart Animation
var barChartDrawn = false;

Set it to true when it runs

function barChart(){
    barChartDrawn = true;

Don't do any of those calculations, or run the function, if it's true

$(window).scroll(function () {
    if (barChartDrawn) return;

Upvotes: 1

Related Questions