How do I add an offset to a scroll detection function?

Refresh

April 2019

Views

14 time

1

I'm having some trouble adding in an option offset to my JS code. I wish to be able to add an offset on when the code initiates on the screen, but can't seem to figure out where I would put the calculation.

I have tried minusing the offset from window.innerHeight but it seems to cause the opposite affect.

if ($('.navbar').hasClass('homepage')) {

    var a = 0;
    function toCommas(number){
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $(window).scroll(function() {

      var oTop = $('.counter-anim').offset().top - window.innerHeight;

      if (a == 0 && $(window).scrollTop() > oTop) {

        var span = $(".counter-anim").find(".counter-value");
        span.each(function() {

          var $this = $(this);
          var countTo = $this.attr('data-count');

          $({countNum: $this.text()}).animate({
            countNum: countTo
          },{
            duration: 1500,
            easing: 'swing',
            step: function() {
              var newNum = toCommas(Math.floor(this.countNum));
              $this.text(newNum);
            },
            complete: function() {
              $this.text(toCommas(this.countNum));
            }
          });
        });
        a = 1;
      }
    });
  };

It should allow me to put in an option offset. Any help/advice is appreciated. Kind Regards.

1 answers

1

You should just be able to create a var and then minus the negative offset from the window.innerHeight.

See below:

if ($('.navbar').hasClass('homepage')) {

    var a = 0;
    function toCommas(number){
      return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    $(window).scroll(function() {

      var optionalOffset = 25; // This has been added
      var oTop = $('.counter-anim').offset().top - window.innerHeight - -optionalOffset; // This has been updated

      if (a == 0 && $(window).scrollTop() > oTop) {

        var span = $(".counter-anim").find(".counter-value");
        span.each(function() {

          var $this = $(this);
          var countTo = $this.attr('data-count');

          $({countNum: $this.text()}).animate({
            countNum: countTo
          },{
            duration: 1500,
            easing: 'swing',
            step: function() {
              var newNum = toCommas(Math.floor(this.countNum));
              $this.text(newNum);
            },
            complete: function() {
              $this.text(toCommas(this.countNum));
            }
          });
        });
        a = 1;
      }
    });
  };

Have a nice day!