Forums

Give help. Get help.

  • # November 7, 2017 at 2:24 pm

    So I’ve got this little script that listens to scroll events:

    $('.item').scroll(function() {
    
      var move = $(this).scrollTop();
    
      ...
    
    });
    

    And this function to throttle events:

    $.restrain = function(delay, callback) {
    
      var executed = 0, debounce,
      throttle = function() {
    
      var elapsed = Math.min(delay, Date.now()-executed),
      remain = delay-elapsed;
      debounce && clearTimeout(debounce);
      elapsed == delay && runIt();
      if (remain) debounce = setTimeout(runIt, remain);
    
      function runIt() {
      executed = Date.now();
      callback.apply(this, arguments);
      }
      }
      return throttle;
    }
    

    Combined, they would look thus:

    $('.item').scroll($.restrain(50, function() {
    
      var move = $(this).scrollTop();
    
      ...
    
    }));
    

    But the problem is that this now no longer refers to the element being scrolled but to window instead.

    Anyone have an idea how I can pass this to the inner function itself?

    # November 7, 2017 at 8:03 pm

    Any suggestions welcome…

    For now I’ve gone with a loop (with is kinda circumventing the issue instead of solving it):

    $('.item').each(function(i) {
    
      $(this).scroll($.restrain(50, function() {
    
        var move = $('.item').eq(i).scrollTop();
    
        ...
    
      }));
    });
    
    # November 8, 2017 at 1:43 am

    Same kind of thing when passing events, which is harder to circumvent in a decent way…

    $('.item').scroll(function(e) {
    
      e.preventDefault();
    
      ...
    
    });
    
    $('.item').scroll($.restrain(50, function(e) {
    

    That e in the second snippet (naturally) won’t work when written like this.

    # November 8, 2017 at 8:34 pm

    Workaround:

    $('.item').scroll(function(e) {
    
      e.preventDefault();
    
      ...
    
    })
    .scroll($.restrain(50, function() {
    
      ...
    
    }));
    

    Meh.

Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag