0

I currently have the following function which effectively retrieves JSON from Django and loads movies via infinite scroll. However, I find that sometimes this event triggers multiple times, and it ends up getting the same page twice.

$(window).scroll(function() {
  var break_point = $(document).height() - ($(window).height() * 1.02);
  if ($(window).scrollTop() >= break_point) {
    var timePeriod = $('.tab-content').find('.active').attr('id');
    var nextPage = $('#'+timePeriod+' ul li:last').attr('data-next');
    if (nextPage) {
      loadMovies(timePeriod, nextPage);
    }
  }
});

What's the best way to stop this listener from executing multiple times per page?

ArKi
  • 681
  • 1
  • 10
  • 22
  • [Is this what you're looking for?](http://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-scrolling) - Also related: [4620906](http://stackoverflow.com/questions/4620906), [8931605](http://stackoverflow.com/questions/8931605) – Rob Hruska Apr 30 '12 at 04:10

2 Answers2

1

Thanks to Rob for the help! I'm just posting what I ended up doing for everyone else's reference. I used the underscore.js library's debounce function.

var infiniteScroll = _.debounce(function() {
  var break_point = $(document).height() - ($(window).height() * 1.02);
  if ($(window).scrollTop() >= break_point) {
    var timePeriod = $('.tab-content').find('.active').attr('id');
    var nextPage = $('#'+timePeriod+' ul li:last').attr('data-next');
    if (nextPage) {
      loadMovies(timePeriod, nextPage);
    }
  }
}, 250);

$(window).scroll(infiniteScroll);
ArKi
  • 681
  • 1
  • 10
  • 22
0

use .one('scroll', function() instead of .scroll(function()

http://api.jquery.com/one/

Thinking about your functionality, you might have to reattach the handler on reload, though. But one() will ensure it only fires once after you attach it.

Colleen
  • 23,899
  • 12
  • 45
  • 75
  • Hey, how would I reattach the handler after it fires? – ArKi Apr 30 '12 at 04:08
  • You could, for example, put the code with one() into a function, and then call that function in your document ready and then call it again on return. Or, you could (same functionality) leave it as is, put it in a function, but the first time you make an ajax (presumably?) call, call unbind, and then call the function again on success. – Colleen Apr 30 '12 at 04:11