0

I have a script that counts to a number when i scroll to an element, but it stopped working in Chrome/Firefox for no reason. However it works fine in Edge.

I tried clearing cache and cookies and disabled extensions, but it still doesn't work.

$(function() {
  var oTop = $('.stats').offset().top - window.innerHeight;
  $(window).scroll(function() {

    var pTop = $('body').scrollTop();
    if (pTop > oTop) {
      start_count();
    }
  });
});
var executed = false; // <= variable to false.

function start_count() {


  if (!executed) { // <= make sure it didn't executed before.

    $('.stats h1').countTo({
      onComplete: function() {
        var elementToPrepend = '<span style="margin-left:4px;">+</span>';
        $(elementToPrepend).hide().appendTo(this).fadeIn();

      }
    });

    executed = true; // <= the count() function already executed

  }

}
.empty-space {
  height: 500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countto/1.2.0/jquery.countTo.js"></script>
<div class="empty-space">
   scroll down...
</div>
<div class="stats">
   <h1 data-from="200" data-to="2000" data-speed="1750" data-refresh-interval="50">200</h1>
</div>
<div class="empty-space">
</div>

Demo link: https://jsfiddle.net/30w9kbfj

Chrome: Version 61.0.3163.79 (Official Build) (64-bit).

Firefox: Version 55.0.3 (64-bit).

OS: Windows 10 64-bit.

If it didn't work for you try using Edge and let me know, any help is appreciated.

Exil
  • 311
  • 2
  • 11
  • 26

1 Answers1

0

So the issue was that Element.scrollTop got updated in Chrome/Firefox, whatever.

I found a workaround by combining Element.scrollTop and document.scrollingElement.scrollTop to make it cross-browser.

$(document.scrollingElement || "body").scrollTop();

Source.

Document.scrollingElement.

Element.scrollTop.

Exil
  • 311
  • 2
  • 11
  • 26