0

I am currently attempting to make a dynamic website where as you scroll down it loads in more elements on the page.

html:

<div>some elements here</div>
<div id="page2"></div>

JavaScript:

var distance = $('part2').offset().top,
    $window = $(window);

$window.scroll(function() {
    if ( $window.scrollTop() >= distance ) {
        $("#part2").append("pages/page2.html");
    }
});

My problem is that it continues to refresh the page as the second element loads in. I need a way to make the second page load in and then stop to listen for scrolling. I do intend to later on implement a third part, so I will have another div for "page3" that will load in another page on scroll. Thanks a lot for help.

  • I don't think `.append()` can load a page, maybe use [`.load()`](http://api.jquery.com/load/) instead. That will still (re)load that page again with every pixel you scroll though, because your `if-clause` will always remain `true` once you've scrolled passed that `distance`. You could set the `distance` to a larger value inside the `if-clause` to fix that. – myfunkyside Oct 18 '16 at 23:10
  • Have you tried browsing this question? http://stackoverflow.com/questions/14035180/jquery-load-more-data-on-scroll – Royts Oct 19 '16 at 03:43

3 Answers3

0

Instead of writing one yourself, you can use a pre-made plug-in? http://jscroll.com/ for example, requires jQuery though.

EdwardM
  • 1,116
  • 11
  • 20
  • I have attempted to use this one before but I had trouble figuring out how to implement it. It would help a lot if you could explain it to me. – Leon Krugliakov Oct 18 '16 at 22:53
0

Update

It looks like you are trying to load the second page inside of the page2 div. If so you should use the load jQuery method.

$("#part2").load("pages/page2.html");

You forgot you the # in your jQuery selector

var distance = $('#part2').offset().top,
Community
  • 1
  • 1
andre mcgruder
  • 1,120
  • 1
  • 9
  • 12
0

Have you tried browsing the answers in this question?

jQuery load more data on scroll

one of the answer is this

$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
       // ajax call get data from server and append to the div
}
});

answer by @deepakssn

Community
  • 1
  • 1
Royts
  • 501
  • 6
  • 14