2

I'm trying to make a number count up when it's within the viewport, but currently, the script i'm using will interrupt the count on scroll.

How would I make it so that it will ignore the scroll and just count up when it's within the viewport? This needs to work on mobile, so even when a user is scrolling on touch. It cannot interrupt the count.

Please see here: http://jsfiddle.net/Q37Q6/27/

(function ($) {

$.fn.visible = function (partial, hidden) {

    var $t = $(this).eq(0),
        t = $t.get(0),
        $w = $(window),
        viewTop = $w.scrollTop(),
        viewBottom = viewTop + $w.height(),
        _top = $t.offset().top,
        _bottom = _top + $t.height(),
        compareTop = partial === true ? _bottom : _top,
        compareBottom = partial === true ? _top : _bottom,
        clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;

    return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};

})(jQuery);


// Scrolling Functions
$(window).scroll(function (event) {
function padNum(num) {
    if (num < 10) {
        return "" + num;
    }
    return num;
}

var first = 25; // Count up to 25x for first
var second = 4; // Count up to 4x for second
function countStuffUp(points, selector, duration) { //Animate count
    $({
        countNumber: $(selector).text()
    }).animate({
        countNumber: points
    }, {
        duration: duration,
        easing: 'linear',
        step: function () {
            $(selector).text(padNum(parseInt(this.countNumber)));
        },
        complete: function () {
            $(selector).text(points);
        }
    });
}

// Output to div
$(".first-count").each(function (i, el) {
    var el = $(el);
    if (el.visible(true)) {
        countStuffUp(first, '.first-count', 1600);
    }
});

// Output to div
$(".second-count").each(function (i, el) {
    var el = $(el);
    if (el.visible(true)) {
        countStuffUp(second, '.second-count', 1000);
    }
});

});
Matt
  • 43
  • 2
  • 5

1 Answers1

1

Your example is more complicated than you're aware, I think. You're doing things in a pretty unusual way, here, using a jQuery animate method on a custom property as your counter. It's kind of cool, but it also makes things a little more complicated. I've had to add a number of things to straighten up the situation.

  1. I went ahead and rewrote your visible plugin, largely because I had no idea what yours was doing. This one's simple!

  2. When your counters become visible, they get a "counting" class so that the counter isn't re-fired on them when they're already counting.

  3. I save a reference to the object you have your custom counter animation on to the data attribute of the counter. This is vital: without that reference, you can't stop the animation when it goes offscreen.

  4. I do some fanciness inside the step function to keep track of how much time is left so that you can keep your counter running at the same speed even if it stops and starts. If your counter runs for half a second and it's set to use one second for the whole animation, if it gets interrupted and restarted you only want to set it to half a second when you restart the counter.

http://jsfiddle.net/nate/p9wgx/1/

(function ($) {

    $.fn.visible = function () {

        var $element = $(this).eq(0),
            $win = $(window),

            elemTop = $element.position().top,
            elemBottom = elemTop + $element.height(),

            winTop = $win.scrollTop(),
            winBottom = winTop + $win.height();

        if (elemBottom < winTop) {
            return false;
        } else if (elemTop > winBottom) {
            return false;
        } else {
            return true;
        }        
    };

})(jQuery);

function padNum(num) {
    if (num < 10) {
        return " " + num;
    }
    return num;
}


var $count1 = $('.first-count');
var $count2 = $('.second-count');

// Scrolling Functions
$(window).scroll(function (event) {
    var first = 25; // Count up to 25x for first
    var second = 4; // Count up to 4x for second

    function countStuffUp(points, selector, duration) {
        //Animate count
        var $selector = $(selector);
        $selector.addClass('counting');

        var $counter = $({
            countNumber: $selector.text()
        }).animate({
            countNumber: points
        }, {
            duration: duration,
            easing: 'linear',
            step: function (now) {
                $selector.data('remaining', (points - now) * (duration / points));
                $selector.text(padNum(parseInt(this.countNumber)));
            },
            complete: function () {
                $selector.removeClass('counting');
                $selector.text(points);

            }
        });

        $selector.data('counter', $counter);
    }

    // Output to div
    $(".first-count").each(function (i, el) {
        var el = $(el);
        if (el.visible() && !el.hasClass('counting')) {
            var duration = el.data('remaining') || 1600;
            countStuffUp(first, '.first-count', duration);
        } else if (!el.visible() && el.hasClass('counting')) {
            el.data('counter').stop();
            el.removeClass('counting');
        }
    });

    // Output to div
    $(".second-count").each(function (i, el) {
        var el = $(el);
        if (el.visible() && !el.hasClass('counting')) {
            var duration = el.data('remaining') || 1000;
            countStuffUp(second, '.second-count', duration);
        } else if (!el.visible() && el.hasClass('counting')) {
            el.data('counter').stop();
            el.removeClass('counting');
        }
    });
});

There's a lot here. Feel free to ask me questions if anything's not clear.

Nate
  • 4,718
  • 2
  • 25
  • 26
  • Hey Nate, thanks for the help. I'm running into an issue though when I paste this into an external js. I literally copy and pasted, but for some reason the counter doesn't work when it's in the viewport, but it actually works when it's NOT in the viewport and I'm scrolled up all the way at the top of the page. Any clues? I'm using jquery 2.0.2 I believe. – Matt Nov 29 '13 at 06:37