mheonyae mheonyae - 25 days ago 6
HTML Question

Script gets triggered at bottom of div instead of top

I want to make a count up script to be triggered when i reach a specific div, but instead of when it reaches top of the div it starts when it reaches the bottom, why so?

my html:

<div id="status_counter" class="status_bar">
<div class="container text-center">
<div class="row">
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="33">0</div></h2>

</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="25">0</div></h2>!-

</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="15">0</div></h2>

</div>
</div>
<div class="col-sm-3">
<div class="counter-item">
<h2><div class="counter" data-count="42">0</div></h2>

</div>
</div>
</div>
</div>
</div>


my counter.js:

var eventFired = false,
objectPositionTop = $('#status_counter').offset().top;

$(window).on('scroll', function() {

var currentPosition = $(document).scrollTop();
if (currentPosition > objectPositionTop && eventFired === false) {
eventFired = true;


$('.counter').each(function() {
var $this = $(this),
countTo = $this.attr('data-count');

$({ countNum: $this.text()}).animate({
countNum: countTo
},

{

duration: 2000,
easing:'linear',
step: function() {
$this.text(Math.floor(this.countNum));
},
complete: function() {
$this.text(this.countNum);
//alert('finished');
}

});



});




}

});


Currently: when is scroll down to the status_counter it doesnt trigger my script until i scroll down to the bottom of it.

I would like my Count up script to be triggered as soon as the status_counter div appears on my screen, so when the top/start of status_counter div reaches the bottom of the screen.

Answer

If I understand your question well this should work:

var eventFired = false,
    objectPositionTop = $('#status_counter').offset().top,
    objectPositionBottom = objectPositionTop;

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

    if (currentPositionBottom > objectPositionBottom && eventFired === false) {
        eventFired = true;

        $('.counter').each(function() {
            var $this = $(this),
            countTo = $this.attr('data-count');

            $({countNum: $this.text()}).animate({
                countNum: countTo
            }, {
                duration: 2000,
                easing:'linear',
                step: function() {
                $this.text(Math.floor(this.countNum));
            }, complete: function() {
                $this.text(this.countNum);         
            }
            });  
        });   
    }
});