Forza Forza - 2 months ago 5x
Javascript Question

How to get infinite scroll to work?

I'm trying to get this infinite load script to work in my project.

Here's my HTML:

<!-- Contents -->
<div id="page-container">
<div id="scroller">
<div id="page_1" class="pagina"></div>
<div id="page_2" class="pagina"></div>
<div id="page_3" class="pagina"></div>
<div id="page_4" class="pagina"></div>
<div id="page_5" class="pagina"></div>
<div id="page_6" class="pagina"></div>

<div id="pages-to-load">
<div id="page_7" class="pagina"></div>
<div id="page_25" class="pagina"></div>

And here's the script:

function scrollalert(){
var pages = document.getElementById("scroller").getElementsByTagName("div");
var currentPageId = pages[pages.length - 1];
//console.log("currentPageId is: "+currentPageId);
var scrollbox = document.querySelector('#page-container');
var scrolltop = $(window).scrollTop();
var scrollheight = scrollbox.scrollHeight;
var windowheight = $(window).height();
var scrolloffset=20;
if(scrolltop>=(scrollheight-(windowheight+scrolloffset))) {
//fetch new items
console.log("loading more pages");

(function() {
var i;
var pagesToLoad = $("#pages-to-load > div").size();
for (i = 0; i < pagesToLoad; i++) {
$.get(pagesToLoad[i].id, function(newitems){
alert('get new page');

Whatever I try, I can't seem to load and append my new pages. Also when scrolling down, my scrollTop and scrollHeight don't change. I'm sure I'm missing something obvious here. Also my pages-to-load is undefined?


Here is one infinite-scroll script of mine using JQuery which works:


    <title>Scroll Troll Page</title>
    <script src=""></script>
    <div id="scrollbox">
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />

<script type="text/javascript">
    $(window).scroll(function () {
        //- 10 = desired pixel distance from the bottom of the page while scrolling)
        if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
        var box = $("#scrollbox");
    //Just append some content here
    box.html(box.html() + "<br /><br /><br /><br /><br /><br /><br />");

in Line:

box.html(box.html + "Place content to expand here");

You can add the content that should be added to your container when reaching the bottom of the page while scrolling.

Working jsFiddle: