Create a infinite scroll page using jQuery


Posted in: interface, javascript | Save to del.icio.us |

Waypoints is a small jQuery plugin that makes it easy to execute a function whenever you scroll to a particular element – a ‘waypoint’. This can be used to highlight when a element comes into view, load additional html or throw a popup. In this post we will use it to create a infinite scroll page.

An infinite scroll page can be useful when you do not want to add pagination, but would rather load the content on the same page when the user requests.

Waypoints requires jQuery, so you need to add that to your page before initializing waypoints.

<script src="jquery-1.4.4.min.js"></script>
<script src="waypoints.js"></script>

The following is how you register an element as a waypoint. When the user scrolls past that element it triggers a waypoint.reached event, which you can then use to run your custom code.

For example if you have a footer element with the following structure, you can attach a function to be executed when that element comes in view.

<footer>
    <div class="container">  
        <p>Footer text</p>
    </div>
</footer>
$(document).ready(function() {
	opts = {
		offset: '100%'
	};
 
        /* Execute the following when the footer comes in view */
	$('footer').waypoint(function(event, direction) {
		alert('You have scrolled to the end of the page.');
 
	}, opts);
});

In the above example we only displayed a alert dialog, but what we instead want is additional data to be appended to the existing content, giving us our infinite page. The following is a example code to create a infinite page by loading additional data from a php server page.

$(document).ready(function() {
	$footer = $('footer'),
	opts = {
		offset: '100%'
	};
 
        /* When the 'footer' element comes in view, 
           the following code is executed */
	$footer.waypoint(function(event, direction) {
		$footer.waypoint('remove');
                /* We get additional data from a php page and 
                   append the same to the end of the page. */
		$.get('more-data.php', function(data) {
			$('#main').append(data);
			$footer.waypoint(opts);
		});
	}, opts);
});

You can find additional options at the waypoints page.

Your thoughts