JavaScript
Article

6 jQuery Infinite Scrolling Demos

By Jérémy Heleine

Infinite scrolling is now a common feature and there are several cases where it is really useful. For instance there are some websites where we simply can’t imagine a good pagination system, like Twitter or even Facebook. Another example of where infinite scrolling can be useful is for a search engine: you’ll want to continue viewing new links while you don’t find the one you want, and a pagination system can slow you down in your research.

If you need to use infinite scrolling for your project, here are six demos that you can use as inspiration to implement it.

Note that, except for the last one, all these demos are written with jQuery and some examples are using jQuery plugins. However, other examples can easily be adapted for vanilla JS without any problem.

1. Infinite Scrolling and Grids

This demo uses the jQuery Masonry plugin together with the Infinite Scroll plugin. The Masonry plugin is good for obtaining fluid grid layouts. The Infinite Scroll plugin by Paul Irish is good at loading pages that already exist (so it is good for your SEO). You can use it to load static pages such as page2.html, page3.html, etc., but this plugin also handle generated pages, such as page.php?p=2, page.php?p=3. However, to use it you need to have a page number to increment in your URLs so, if you have pages such as page.php?data=xxx, then this plugin is not for you.

Usage – HTML

<div class="grid">
	<div class="grid-item grid-item-2">
		<p>content</p>
	</div>
	…
</div>

<!-- The next page which content will be loaded when scrolled -->
<nav id="pagination">
	<p><a href="page-2.html">Page 2</a></p>
</nav>

Usage – jQuery

$(document).ready(function() {
	var grid = $('.grid');

	grid.masonry({
		itemSelector: '.grid-item',
		columnWidth: 200
	});

	grid.infinitescroll({
		// Pagination element that will be hidden
		navSelector: '#pagination',

		// Next page link
		nextSelector: '#pagination p a',

		// Selector of items to retrieve
		itemSelector: '.grid-item',

		// Loading message
		loadingText: 'Loading new items…'
	},

	// Function called once the elements are retrieved
	function(new_elts) {
		var elts = $(new_elts).css('opacity', 0);

		elts.animate({opacity: 1});
		grid.masonry('appended', elts);
	});
});

2. Infinite Scrolling through Blog Posts

This demo doesn’t use any plugin or library to handle the infinite scrolling feature. Each time the end of the page is reached by the user, it loads a new post, generated by a PHP script that echoes the corresponding HTML code. The demo never reaches the end of content but you can achieve this by, for example, echoing an empty string when there is no more posts to show. We display a loading image at the end of the page, in the spirit of Twitter.

Note that, in the live demo below, the new posts are generated by a JavaScript function, as we can’t use a PHP script in CodePen.

See the Pen Infinite Scrolling through Blog Posts by SitePoint (@SitePoint) on CodePen.

Usage – HTML

<ul id="posts">
	<li>
		<article>content</article>
	</li>

	…
</ul>

<p id="loading">
	<img src="images/loading.gif" alt="Loading…" />
</p>

Usage – jQuery

$(document).ready(function() {
	var win = $(window);

	// Each time the user scrolls
	win.scroll(function() {
		// End of the document reached?
		if ($(document).height() - win.height() == win.scrollTop()) {
			$('#loading').show();

			$.ajax({
				url: 'get-post.php',
				dataType: 'html',
				success: function(html) {
					$('#posts').append(html);
					$('#loading').hide();
				}
			});
		}
	});
});

3. Infinite Scrolling through Images

This demo loads in images on infinite scroll and never reaches the end. It uses the jQuery Endless Scroll plugin which can be customized to trigger loading x number of pixels from the bottom of the screen. The demo clones the same images and inserts them at the end of the list and so on, but the script can be customized to load the images from different sources quite easily.

See the Pen Infinite Scrolling through Images by SitePoint (@SitePoint) on CodePen.

Usage – HTML

<ul id="images">
	<li>
		<a href="https://www.pexels.com/photo/mist-misty-fog-foggy-7919/">
			<img src="https://pexels.imgix.net/photos/7919/pexels-photo.jpg?fit=crop&w=640&h=480" alt="" />
		</a>
	</li>

	…
</ul>

Usage – jQuery

$(document).ready(function() {
	$(window).endlessScroll({
		inflowPixels: 300,
		callback: function() {
			var $img = $('#images li:nth-last-child(5)').clone();
			$('#images').append($img);
		}
	});
});

4. Infinite List of Numbers

This demo uses the same plugin as the previous one but we have applied the infinite scroll to a list with its own vertical scrollbar. As you scroll down the numbers are simply appended as list items.

See the Pen An infinite list of numbers by SitePoint (@SitePoint) on CodePen.

Usage – HTML

<ul id="numbers">
	<li>1</li>
	<li>2</li>
	<li>3</li>
	<li>4</li>
	<li>5</li>
	…
</ul>

Usage – jQuery

$(document).ready(function() {
	var offset = $('#numbers li').length;

	$('#numbers').endlessScroll({
		fireOnce: false,
		fireDelay: false,
		loader: '',
		insertAfter: '#numbers li:last',
		content: function(i) {
			return '<li>' + (i + offset) + '</li>';
		}
	});
});

5. Infinite Spreadsheets

This demo uses the same technique as demo 2 to detect when the user has reached the end of the document, not just vertically but also horizontally. Each time one end is reached we add a new row or a new column to the table. It is exactly the kind of script we could write if we want to create a spreadsheets application.

Note that all the cells are empty. The rows and columns indexes are generated with CSS counters so that we don’t need to calculate them by ourselves.

See the Pen Infinite Spreadsheets by SitePoint (@SitePoint) on CodePen.

Usage – HTML

<table id="spreadsheet">
	<tr>
		<td></td>
		<th></th>
		…
	</tr>
	<tr>
		<th></th>
		<td></td>
		…
	</tr>
	…
</table>

Usage – jQuery

$(document).ready(function() {
	var win = $(window);
	var doc = $(document);

	// Each time the user scrolls
	win.scroll(function() {
		// Vertical end reached?
		if (doc.height() - win.height() == win.scrollTop()) {
			// New row
			var tr = $('<tr />').append($('<th />')).appendTo($('#spreadsheet'));

			// Current number of columns to create
			var n_cols = $('#spreadsheet tr:first-child th').length;
			for (var i = 0; i < n_cols; ++i)
				tr.append($('<td />'));
		}

		// Horizontal end reached?
		if (doc.width() - win.width() == win.scrollLeft()) {
			// New column in the heading row
			$('#spreadsheet tr:first-child').append($('<th />'));

			// New column in each row
			$('#spreadsheet tr:not(:first-child)').each(function() {
				$(this).append($('<td />'));
			});
		}
	});
});

6. Infinite Scrolling + Pagination

There are cons against infinite scrolling: if it is not implemented well, the user experience can be broken. If you let the user load an infinite list, they can lose their place after a while. That’s a thing that never appends with a traditional pagination system. However, pagination requires actions from the user that aren’t necessary with infinite scrolling.

These two facts gave Tim Severien an idea: what if we combined infinite scrolling and pagination, to take the advantage of both methods? The result is this last demo.

An initial page is shown to the user. When the user scrolls down and reaches the bottom of the page, a new page is loaded automatically. Here we enjoy the simplicity from infinite scrolling. But the new things come from a list fixed at the bottom of the screen.

Initially hidden, this list is filled, each time a new page is loaded, with the number of this page. That way, if the user wants to retrieve the second page, they can without any effort by hitting the corresponding number.

See the Pen Infinite Scroll + Pagination by SitePoint (@SitePoint) on CodePen.

Usage – HTML

<div class="article-list" id="article-list"></div>
<ul class="article-list__pagination article-list__pagination--inactive" id="article-list-pagination"></ul>

Usage – JavaScript

Please note that this code uses ES6, but you can easily convert it to ES5.

function getPageId(n) {
	return 'article-page-' + n;
}

function getDocumentHeight() {
	const body = document.body;
	const html = document.documentElement;
	
	return Math.max(
		body.scrollHeight, body.offsetHeight,
		html.clientHeight, html.scrollHeight, html.offsetHeight
	);
};

function getScrollTop() {
	return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
}

function getArticleImage() {
	const hash = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
	const image = new Image;
	image.className = 'article-list__item__image article-list__item__image--loading';
	image.src = 'http://api.adorable.io/avatars/250/' + hash;
	
	image.onload = function() {
		image.classList.remove('article-list__item__image--loading');
	};
	
	return image;
}

function getArticle() {
	const articleImage = getArticleImage();
	const article = document.createElement('article');
	article.className = 'article-list__item';
	article.appendChild(articleImage);
	
	return article;
}

function getArticlePage(page, articlesPerPage = 16) {
	const pageElement = document.createElement('div');
	pageElement.id = getPageId(page);
	pageElement.className = 'article-list__page';
	
	while (articlesPerPage--) {
		pageElement.appendChild(getArticle());
	}
	
	return pageElement;
}

function addPaginationPage(page) {
	const pageLink = document.createElement('a');
	pageLink.href = '#' + getPageId(page);
	pageLink.innerHTML = page;
	
	const listItem = document.createElement('li');
	listItem.className = 'article-list__pagination__item';
	listItem.appendChild(pageLink);
	
	articleListPagination.appendChild(listItem);
	
	if (page === 2) {
		articleListPagination.classList.remove('article-list__pagination--inactive');
	}
}

function fetchPage(page) {
	articleList.appendChild(getArticlePage(page));
}

function addPage(page) {
	fetchPage(page);
	addPaginationPage(page);
}

const articleList = document.getElementById('article-list');
const articleListPagination = document.getElementById('article-list-pagination');
let page = 0;

addPage(++page);

window.onscroll = function() {
	if (getScrollTop() < getDocumentHeight() - window.innerHeight) return;
	addPage(++page);
};

Conclusion

We’ve looked at six different examples of implementing infinite scrolling. No matter what you’re trying to build, you should be able to use one of these techniques to achieve the result you want. As always, we’d love to hear your thoughts: have you built anything cool with one of these plugins or techniques? Do you have a favorite plugin that you think should have been mentioned? Let us know in the comments!

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

  • http://tutsmais.com.br/blog/ Ofelquis

    Great.. =D

    • http://jquery4u.com/ jQuery4u

      Thanks!

      • http://dentaldev.tk/index.php/ Noman

        Thanks for sharing such a nice info

  • http://www.gbin1.com terry

    It’s kind of cool stuff!

  • Pingback: Tweet-Parade (no.48 Nov-Dec 2011) | gonzoblog.nl()

  • avner

    great!
    has anyone already integrated this plugin with Wicket using WiQuery?

    • http://dentaldev.tk/index.php/ Noman

      I am looking foe new developer virtually if any one willing to work then contact me

  • coffeeyesplease

    Fantastic stuff.
    Thanks a million

    • http://jquery4u.com/ jQuery4u

      No worries! :)

  • Eliza

    Hi
    I am using it for images and have used fancy box to open the images and a box but the infinite scroll doesn’t work. The loading box comes up but the page doesn’t appear… this isn’t working on IE9 windows 7… PLEASE HELP!!!

    • http://jquery4u.com/ jQuery4u

      Hi Eliza,

      Sounds like a typical IE bug, does it work in any other versions of IE?

      Could you post a URL so I could take a look for you?

      Thanks,
      Sam

      • Eliza

        Hi Sam,

        Thank you the URL is http://www.optsydney.com.au/testinghub/gallery.php

        The issue I’m having is that once you reload the page you can no longer scroll down and see all the pages come up and the fancy box grabs whatever image it likes when you click on an image….

        Really appreciate any help you can give me :)

        Thanks,
        Eliza

        • Eliza
          • http://jquery4u.com/ jQuery4u

            Thanks Eliza, very nice site! Can’t see any bug, It’s working great in Chrome Canary but yes I do see the bug in IE9 / both on Win7.

          • Eliza

            Thank you :) Do you know what I could do to fix it?

          • http://jquery4u.com/ jQuery4u

            This is a tough one, IE bugs usually are unpredictable. It looks like this function could be your culprit. 

            $newElems.animate({ opacity: 1 }); 

            Try added a new css class with opacity covered for different browsers including IE then set the class instead of using animate, this should fix it. Animate doing the same as fadeIn with opacity 1.

            $newElems.addClass(‘show’).fadeIn(); 

            /* css class to show all images */.show {/* Required for IE 5, 6, 7 *//* …or something to trigger hasLayout, like zoom: 1; */width: 100%; /* Theoretically for IE 8 & 9 (more valid) *//* …but not required as filter works too *//* should come BEFORE filter */-ms-filter:”progid:DXImageTransform.Microsoft.Alpha(Opacity=100)”;/* This works in IE 8 & 9 too *//* … but also 5, 6, 7 */filter: alpha(opacity=100);/* Older than Firefox 1.0 */-moz-opacity:1.0;/* Safari 1.x (pre WebKit!) */-khtml-opacity: 1.0;/* Modern!/* Firefox 0.9+, Safari 2?, Chrome any?/* Opera 9+, IE 9+ */opacity: 1.0;}
            full code snippet in <div id="contentGallery"  …——————————————————————-  $(window).load(function(){    var $container = $('#container');    $container.imagesLoaded(function(){      $container.masonry({        itemSelector: '.box',        columnWidth: 1      });    });    $container.infinitescroll({ debug           : false,      navSelector  : '#page-nav',    // selector for the paged navigation      nextSelector : '#page-nav a',  // selector for the NEXT link (to page 2)      itemSelector : '.box',     // selector for all items you'll retrieve      loading: {          finishedMsg: 'No more pages to load.',          img: 'http://i.imgur.com/6RMhx.gif'        }      },      // trigger Masonry as a callback      function( newElements ) {        // hide new items while they are loading        var $newElems = $( newElements ).css({ opacity: 0 });        // ensure that images load before adding to masonry layout        $newElems.imagesLoaded(function(){          // show elems now they're ready          $newElems.animate({ opacity: 1 });          $container.masonry( 'appended', $newElems, true );        });      }    );  });

            Press F12 in IE to open up developer tools to inspect.Thanks,
            Sam

          • http://jquery4u.com/ jQuery4u

            Hi Eliza,

            Code is slightly messy here, try this fiddle: http://jsfiddle.net/ay77t/Thanks,
            Sam

          • http://jquery4u.com/ jQuery4u

            How’d you go Eliza? Did it fix it?
            Sam

          • http://dentaldev.tk/index.php/ Noman

            Eliza Wana virtual Job?>
            Contact me

  • Pingback: 10 Lightest of the Lightweight jQuery Plugins | jQuery4u()

  • Pingback: Implemenitng Infinite Scrolling with jquery - feed99()

  • Pingback: Implemenitng Infinite Scrolling with jquery()

  • Pingback: 10 Cool Infinite Scrolling Effects That Can Enhance Your Website's Navigation | Design Superstars()

  • Pingback: Grids, Paging and Infinite Scrolling « devioblog()

  • Gus

    Thank you! Very helpfull! I have this problem of many scroll events calling the function almost simultaneously… any suggestion on how to order this? I need only one trigger at a time… Thank You!

    • james

      I have the same issue, Jquery fires multiple times loading the same content. I have used a session to try to prevent this however the jquery is firing simultaneously so my session is having any effect. I tried using a timmer to prevent any actions happening simultaneously but all it does is que the events and load them after 500 miliseconds. This seems to be pretty useless to me. And the fact you havent answered the question about this problem suggests you have no solution! that makes this whole page a complete waiste of time. If your reading this move ontop a different tutorial as this one is a waste of your time!

      • http://jquery4u.com/ jQuery4u

        Sorry for late reply was busy working on the new site, My solution in the past has been to simply declare a variable, say loadingInProgress = false, then set this to true before you call for new items then in the callback you can set it back to false. This works as a quick solution but there probably a better way. Let me know how you go. Also, patience is a virtue the solution will come.
        Sam

        • marcjuchli

          @41ba00bff9f2549810c05aeee3ca8beb:disqus @801a266749dae16ca0e4e9d394840769:disqus did you find a solution here?
          @jquery4u:disqus unfortunately the trick with the true/false didn’t work for me as firefox will call all the upcoming events at once instead of waiting until .append() is completed. Any idea here?

        • Max

          Can you show us the code for this quick solution: loadingInProgress = false …
          Thanks a lot!

      • Max

        I have the exact same problem: jQuery fires as many as 50-90 times before it stops. So I went over to Demo5 instead. It doesn´t have the same problem, BUT, it won´t work in my iPhone.
        Anybody knows how to make it work for iPhone?
        Thanks

  • http://www.facebook.com/suavekhmer Sasha Merkushev

    Great script (1). The only problem it doesn’t work with Lytebox – on second and subsequent pages… What a shame…

    • http://dentaldev.tk/index.php/ Noman

      i also face this problem

  • http://nizamilputra.com/ Rizqi Nizamil Putra

    How can I add “a loop for loading to reach the end” on “Infinite Scrolling Demo 2”, so I can limit the post. Could you give me a sample script?

    • TotalniPortali

      Yes, I want to know that too! Help anyone, please…

  • TotalniPortali

    How can I add “a loop for loading to reach the end” on “Infinite
    Scrolling Demo 2”, so I can limit the post. Could somebody please give me a sample
    script?

  • Shantanu

    HI,

    I am using demo1 . It is working properly for me. I have an issue in it is, can we minimize space between images? I do not want space in images.

    How to do this?

    • http://dentaldev.tk/index.php/ Noman

      You Should Use Angular JS , it will resolve your issue

  • Paul

    The 1st one for me doesn’t work for div location. I’ve been trying to implement “localMode” for this plugin for all day but I couldn’t do that. Wierd behavior of this solution persuaded me to not use it in my project.

  • Pingback: 16 jQuery Infinite Scroll Plugin()

  • Rana

    Hi, I like the 5th demo & I want to use, but I don’t know where can I find the source code ?

    • http://dentaldev.tk/index.php/ Noman

      Oye Rana
      You are BC

    • Geo

      If you’ve found a soluton for this, could you please let me know?

  • Pingback: Tuned | Add Infinite Scroll to your WordPress Theme in 3 Steps()

  • http://www.facebook.com/profile.php?id=100001088220424 Max Stranger

    thanks :D

  • Pingback: 5 JQuery Infinite Scrolling Demos » My Virtual Word()

  • jithin

    wow.splendid

  • sweta

    i had been trying that number 1 but it seems not working… can u email me that demo file so that i can check?

    • http://dentaldev.tk/index.php/ Noman

      Sweeta actually your framework not suport this function

  • Sahra

    Hi, I used pagening to display my product records .Now I ‘d like to
    use demo1 as endless scrolling to list them.How should I use demo 1
    ?Please help me to change my pagening way to infinite scrolling.thanks

  • Pingback: Top 10 jQuery scrolling plugins()

  • mob4eg

    $(function() {
    //More Button
    $(‘.more’).live(“mouseover mouseout”,function domore()
    {
    var ID = $(this).attr(“id”);
    if(ID)
    {
    $(“#more”+ID).html(”);

    $.ajax({
    type: “POST”,
    url: “newproducts.php?brand= “,
    data: “lastmsg=”+ ID,
    cache: false,
    success: function(html){
    $(“#center_content”).append(html);
    $(“#more”+ID).remove();
    }
    });
    }
    else
    {
    $(“.morebox”).html(‘ ↑ العودة
    إلي الأعلي ↑
    ‘);
    }
    return false;
    }); });

    how do infinite scroll or when scroll show . please with this code

  • Ashly

    Hi sam, I like the 5th demo & I want to use it. Can u provide me some help related that.

  • kkalbat

    I’m trying to implement demo2 in WordPress, no luck though. I’m assuming you are not using any plugins for demo 2, right? Just the files on Github

  • Pingback: Websiteniz için Seçilmiş 5 JQuery Infinite Scroll Uygulaması - Metinbelgesi.Net()

  • Pingback: Class | jessInteractive()

  • http://dentaldev.tk/index.php/ Noman

    My Magneto Site id build in Masonry Library , i want to add , AJAX page loader function in page but it fails. Same like Facebook posts loads when we scroll down

  • https://www.behance.net/dannyfelipe Danny Felipe

    Hello Sam, how are you?

    I would like a little help, in example number 2, how could I make him not be infinite? For the if he falls to the second condition and show “No more posts to show.”

    thank you

  • http://www.webmastersun.com/ Webmaster Sun

    Not bad, I will try to apply for my blog.

  • Kew Mei

    Hey~ GREAT STUFF!!!
    I would like to use the infinite scrolling in DEMO 1 in my opencart?….is it possible??…can help??…

  • Tony Yau

    Demo 3 (endless scroll) has the fastest loading speed and great flexibility.

  • pieboy007

    what about infinity scroll by airbnb http://airbnb.github.io/infinity/

  • INVISIBLEpussy .

    Demo 3 doesn’t work for me. Wondering what could I fuck up in there…

  • Max

    I am trying to use Demo5 and it works in my computer. But it won´t work on my iPhone. Is there any way to make it work in an iPhone?
    Please
    Thanks for help

  • Mufleeh Sadique

    Hi,

    Can any of these used to set the number of items queried dynamically?

  • fieg

    Have a look at Infinite Ajax Scroll (http://infiniteajaxscroll.com). It is SEO-friendly because it progressively enhances your existing server-side pagination.

    • Darqul

      hey fieg, it’s hard to reach you since all your comments are locked. I have a question about your infinite scroll lib. Does this take into consideration that let’s say only 10 posts out of 1000 are visible in the browser so it doesn’t keep all the previously loaded content in memory?

      So let’s say there are 1000 posts. First 10 posts are loaded and when the user scrolls down 4 additional posts are loaded. Fine. Now 14 posts are in memory. The user scrolls down and down and 30 posts are in memory. But the user can see only 10. Are the previous 20 posts removed from memory and loaded again or are they kept in memory?

  • Casper

    Hi Sam, I want to use your plugin for wordpress. Now I have integrate it with my theme, but the load will be very hard and fast. A very fast opacity. How can I fix this? Also I have a second scrollbar inside my container now, after adding the scripts. Can I fix this to? Like to hear from you!

    Casper

  • Rachid Alami

    Great job, there is another one, it may help you too:
    Ajax Scroll Paging Using jQuery, PHP and MySQL
    http://www.bewebdeveloper.com/tutorial-about-ajax-scroll-paging-using-jquery-php-and-mysql

  • Swapnil Daga

    Great Job. Works like charm . Could implement #2 in very less time!

  • Abhishek

    i am using ajax scroll . i am using it for my social netwroking project. but when i click on the like button or comment button on the posts which is being appended coz of ajax scroll, the page refreshes and page scrolls down to the first 5 rows which exist on that page by default. i am using location.reload for refresh . i tried saving the scroll position but still after refreshing its not scrolling back to the post i have commented or liked. any suggestion pls anyone?

  • Jhyland

    How can I make this only load like X items via AJAX, and when all of the items are loaded… stop?

  • Nate

    Hi, Demo links are broken

  • vitmalina

    Thanks for the interesting post. I absolutely agree that infinite scroll should completely replace pagination as it is much more practical. However, I did like the idea you implemented in one of the examples, where pagination comes on bottom when you scroll too far. I think it might be a good idea.

    Also, I noticed that in your examples you only add items on the bottom, but do not remove from the top (correct me if I am wrong). I did implement an infinite scroll grid few years back and noticed that if number of nodes in browser goes over 20-30k, it becomes really sluggish. If it is more then 50k browser might actually crash (depending on your memory). I have posted my findings here http://w2ui.com/web/blog/7/JavaScript-Grid-with-One-Million-Records.

  • James Hibbard

    That line was actually present in the original article that Jérémy rewrote (so not actually written by him).

    Nonetheless, it’s a fair point (although you could have made it more constructively). We’ve updated it to read:

    var $img = $('#images li:nth-last-child(5)').clone();
    $('#images').append($img);

  • Robert Smith

    That last one works really well for me. Clean and simple, and no 3rd party plugin required! It was easy to adapt to my needs.

  • upset guy

    this is not LOAD more but SHOW more… it is HUGE difference

  • Anandan K

    win.scroll triggering twice what should i have to do

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.