Skip to content Skip to sidebar Skip to footer

Jquery - How Do I Get My Counter To Load Only When In View?

I am super new to tinkering around with jQuery. I found a solution for a counter that counts up that serves the purpose for showing savings in %. The problem that I have with it,

Solution 1:

You can manipulate your script using scroll event.

functionisScrolledIntoView(elem) {
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
var message = $('#message');
$(window).scroll(function() {
  if (isScrolledIntoView('#hiddenElem')) {
    message.text("Visible");
  } else {
    message.text("Invisible");
  }
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><h3style="position:fixed;top: 0;left: 0;background: white"id="message"></h3><br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<br>Hello..
<divid="hiddenElem">HiddenElem</div>

In your case, try this:

$(window).on('scroll', function () {
    if (isScrolledIntoView('#hiddenElem')) {
        $('.number-count').countTo();
        $(window).off('scroll');
    }
});

Post a Comment for "Jquery - How Do I Get My Counter To Load Only When In View?"