1

I am trying to implement an "infinite-scroll" behaviour to load some photos on a page and I'm using the following JavaScript to do so:

$(document).ready(function(){
  $(window).scroll(function(){
      var wintop = $(window).scrollTop(), docheight = $(document).height(), winheight = $(window).height();
      var  scrolltrigger = 0.10;
      if  ((wintop/(docheight-winheight)) > scrolltrigger) {
         console.log('scroll bottom');
         lastAddedLiveFunc();
      }
  });
});

By default I would like to fill up the users page with just enough photos to throw in a scroll bar - otherwise the above JavaScript would never fire (if only 3 images are loaded say). The photos are loaded with an ajax call at the end of

lastAddedLiveFunc()

Any idea how I could achieve this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user714852
  • 2,054
  • 4
  • 30
  • 52

1 Answers1

1

He is a jsFiddle I made that does what I think you are looking for: http://jsfiddle.net/pseudosavant/FENQ5/

Basically any time the position of the bottom of the window gets within X pixels of the bottom of the document I add some content.

Javascript:

$(document).ready(function(){
    $(window).scroll(function(){
        var docBottom = $(document).height();
        var winBottom = $(window).height() + $(window).scrollTop();
        var scrollTrigger = $(window).height() * 0.25;

        if ((docBottom - scrollTrigger) < winBottom) {
            $("#container").append("<div class='box red'></div>");
            console.log("added more");
        }
    });
});
pseudosavant
  • 7,056
  • 2
  • 36
  • 41
  • hi pseudosavant - thank you for the fiddle. The code I am running does something similar already. The trouble I'm having is shown in the adapted fiddle (http://jsfiddle.net/FENQ5/3/). If the window cannot be scrolled the code is never fired. I am trying to fire the image-loading code automatically and stop when code until the window can be scrolled at which point the images are only loaded using the window.scroll function. – user714852 Feb 16 '12 at 17:56
  • 1
    Check out this fiddle: http://jsfiddle.net/pseudosavant/YAS8P/ I made the function that adds the elements to not be inline anymore. I bind that function to the `scroll` event, and then repeatedly run the function until the document height is greater than the window height. – pseudosavant Feb 21 '12 at 18:07