Infinite scroll

2015-03-13 11:59

Keywords: javascript, show, reveal

This has nothing to do with Textpattern, except this forum post. The question was how to easily implement an infinite scroll. Here you can test the proposed solution in action. Adapting it to your page template should be straightforward.

First, include the necessary JS libraries (you can download them to your server, of course) in the <head /> of your template:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://www.artzstudio.com/files/jquery-boston-2010/jquery.sonar/jquery.sonar.min.js"></script>

Now, suppose that the HTML <body /> of your page contains this:

<main>
<!-- contains stuff we want to be loaded, like articles -->
...
<a rel="prev" class="paginator-prev" href="next_page_url">Older</a>
...
</main>

For testing purposes, my next_page_url will point to this very article, but you should use <txp:older/newer /> tags to construct links, for example

<txp:variable name="older" value='<txp:older />' />
<txp:if_variable name="older" value>
	<a class="paginator-prev" href='<txp:variable name="older" />'>Older</a>
</txp:if_variable>

Now, include the forum snippet somewhere at the end of your page:

<script>
(function($){
var $main = $("main").first();
$.fn.doScroll = function() {
	var $href = $(this).attr("href");
	$("<div />").load($href + " main > *", function() {
		$(this).find("a.paginator-next").one("scrollin", $.fn.doScroll);
		$main.append($(this).children());
		$(this).remove();
	});
};
$("a.paginator-next").one("scrollin", $.fn.doScroll);
})(jQuery);
</script>

Now scroll to the bottom of the page. As soon as the Next stop link below gets into the viewport, a new copy of this article’s <main /> section will be appended.

I have tested it in recent Firefox, Chrome and IE desktop versions, please let me know if it works for you.

Page 1 of 5 | Next stop »