HubSpot / odometer

Smoothly transitions numbers with ease. #hubspot-open-source
http://github.hubspot.com/odometer/docs/welcome
MIT License
7.3k stars 712 forks source link

Initiate animation on viewport #150

Open Ignitis opened 6 years ago

Ignitis commented 6 years ago

Hi,

Is there any way I can initiate the odometer animation as soon as the element is in the viewport?

I need to use odometer on a component which is on the 3rd fold of the webpage. I want it to animate as soon as that component is visible in the viewport.

Thank you. Pri

jason-mares commented 6 years ago

It's possible using jQuery to initiate when the odometer class gets into the viewport:

` $(document).ready(function(){

$.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('resize scroll', function() {
  $('.odometer').each(function() {
    if ($(this).isInViewport()) {

      setTimeout(function(){
        $('.odometer').html(240000);
      }, 0);
    } else {
    }
  });
});

}); `