Thursday, August 15, 2013

How to Implement Infinite Page Scroll Effect in Static Webpages [Tutorial]

Users of popular social networks like Twitter and Tumblr must be familiar with infinite scrolling. This effect is a wonderful dynamic replacement for pagination links where the user doesn’t need to wait for a page refresh. All the external content is loaded dynamically and appended into your content wrapper.

featured thumbnail tumblr infinite loading screenshot

But the problem with this effect is how difficult it can be to setup. WordPress users have their choice of plugins to automatically insert this effect onto archive & category pages. However Web developers working in basic HTML5/CSS3 are forced to use some other solutions.

In this article I want to present two of my favorite plugins for infinite scrolling applied to static Web content. Both of these examples are useful because of how they handle data requests. Some users may be interested in loading static HTML while others need to include backend languages such as PHP or Ruby. Between both of these jQuery plugins we can find a useful solution to fit any Web project.

Infinite Scroll

Infinite Scrolling jquery plugin open source preview

I want to start out with arguably the most popular jQuery plugin infinite scroll. This was created by Paul Irish and can also be found in the WordPress plugins repository. Most users have given very high ratings for the plugin and it appears to still be supported in the newly released WP 3.5.1.

jquery plugin infinite scroll web design interface

However coding your own custom loader is a tad more difficult. We need to use some jQuery method calls and pass in the related data inside our layout. Any infinite loading plugin will require a series of important elements on the DOM. These include the previous/next page anchor links, along with the content wrapper which should hold the new data.

<!doctype html>
  <html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Infinite Scroll Testing</title>
    <meta name="author" content="Jake Rocheleau">
    <link rel="shortcut icon" href="http://www.hongkiat.com/blog/favicon.ico">
    <link rel="icon" href="http://www.hongkiat.com/blog/favicon.ico">
    <link type="text/css" rel="stylesheet" media="all" href="style.css">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript" src="jquery.infinitescroll.js"></script>
    <script type="text/javascript" src="manual-trigger.js"></script>
  </head>
  

My demo is based off the original demo which can be found in the Github repo. You should download a copy of the script or my script since we will need a series of documents for this to work.

Obviously I have included the latest release of jQuery, along with the infinite-scroll plugin and another JS file named manual-trigger.js. I found an excellent post on Stack Overflow which goes into a bit of detail for why this JS script aides the effect.

Loading External HTML Pages

My stylesheet is also the original copied from the demo, but we really do not need to worry much about CSS styles. The paged documents would still load even if we removed all the padding and font styles. But you can see everything has been consolidated into the header except for the JS function which we’ll look into now.

The inner page body is held inside a div with the ID #content and we need to reference this in jQuery. Also the navigation link has the ID #next which is crucial for the pages to load properly. I have copied the entire script block element so we can see how this method is called on the page.

<script type="text/javascript">
  $(document).ready(function(){
  	$('#content').infinitescroll({
  		navSelector: "#next:last",
  		nextSelector: "#next:last",
  		itemSelector: "#content",
  		debug: false,
  		dataType: 'html',
      maxPage: 4,
  		path: function(index) {
  			return "index" + index + ".html";
  		}
  		// appendCallback	: false, // USE FOR PREPENDING
      }, function(newElements, data, url){
        // used for prepending data
      	// $(newElements).css('background-color','#ffef00');
      	// $(this).prepend(newElements);
      });
  });
  </script>
  

The difference between navSelector and nextSelector is subtle, but definitely important. Your navigation selector can be the element which contains the entire navigation. This may be a div containing multiple pages or even two buttons with previous/next page. However the next selector is solely targeting your specific anchor link which points towards the next page.

The “path” value is very important because this is labeling each page we need to request. The parameter may accept a string value or a custom function returning to each new page. For my demo we are using some of the sample code to include three external index pages. The index variable may be passed into the function and you can perform logic to determine which page needs to be loaded next.

Much of this JavaScript code may be placed into an external document if you’d like to clean up the frontend. I would argue that Infinite Scroll does have a potentially stressful learning curve if you are not familiar with jQuery. But it works perfectly fine when all your files are in order. The biggest downside is that you can only load HTML, JSON, or XML pages into the document. It is unlikely we will ever get support for dynamic PHP, ASP, or Python for a backend solution.

jQuery ScrollPagination

jquery scrollpaginate plugin live demo

Here we have another great jQuery plugin which was developed by Anderson Ferminiano. I would argue that ScrollPagination is also initially very difficult to pick up, but it is well worth the effort. You can get more information from the scrollPagination homepage which also includes a live demo.

I have ported a few sample codes into my own layout and built a great demo loading content through PHP. But first you should grab a copy off the Github repo which does include sample files and a brief demo. After unzipping the contents we only need one file named scrollpagination.js to get the effect working. Also we need to include a recent version of jQuery, but that should be assumed.


  <div id="w">
   <h2>Infinite Loading Demo</h2>
   
   <div id="content">
     <p>This is the main content element. All the infinite scroll content will load into this div.</p>
   </div>
   
   <div class="loading" id="loading">Loading please wait...</div>
   <div class="loading" id="nomoreresults">Sorry, no more results to display.</div>
  </div>
  

You will notice my HTML code is much smaller for this example. The two div elements at the bottom of the page should be hidden by default. These will only show up when the plugin has been activated to either load new content, or has reached the end of the content. ScrollPagination actually has a parameter to limit the number of new HTML DOM elements we want to append onto the page.

JS Function Parameters

The most important part of getting this function to work is passing the proper data into the correct variables. Compared to the previous Infinite Scroll plugin we are looking at a much larger block of data. Some of these parameters are referencing functions to call elements when there are new objects to load, and when we have exhausted the list of all objects.

var page = 0;
  $(function(){  
  	$('#content').scrollPagination({
  		'contentPage': 'ajax.php', // the url you are fetching the results
  		'contentData': { 'page': page }, 
  		'scrollTarget': $(window),
  		'heightOffset': 10,
  		'beforeLoad': function(){ 
  		  // before load function, you can display a preloader div
  			$('#loading').fadeIn();	
  		},
  		'afterLoad': function(elementsLoaded){
  			 $('#loading').fadeOut();
  			 var i = 0;
  			 $(elementsLoaded).fadeInWithDelay();
  			 page++;
  			 if ($('#content').children().size() > 140){ 
  			   // if more than 140 results already loaded, then stop pagination
  			 	$('#nomoreresults').fadeIn();
  				$('#content').stopScrollPagination();
  			 }
  		}
  	});

So the parameter contentPage will pick up whatever we need and pass it into the page via Ajax. This means we can load dynamic content and still have it parsed by our server. In this example I am pulling XML data from YouTube and looping through the results in PHP to return a list of videos and thumbnails.

The contentData parameter is also good to use if you need to pass further data into each ajax request. This may be left empty and the plugin will still function properly. But in my example we can pass in the paged value for each loading call and increase the page by +1 each time. Unfortunately I have yet to find a method of getting this value into the backend PHP code. But it can be just as useful in the JavaScript functions.


  // code for fade in element by element
  	$.fn.fadeInWithDelay = function(){
  		var delay = 0;
  		return this.each(function(){
  			$(this).delay(delay).animate({opacity:1}, 175);
  			delay += 100;
  		});
  	};
  		   
  });

At the very bottom of our ScrollPagination method we can see another custom bit of code. This does not require any editing from the user’s end, we just need to ensure that the function works and will be included along with the script codes. fadeInWithDelay will push the same jquery .animate() method onto any of the page elements we need.

This makes it a lot easier rather than copying the same animation codes onto each section in the plugin. Although admittedly this would look much nicer if these codes were stored in a separate JS file (which is possible). However the most redeeming quality of ScrollPagination must be the ability to process backend languages.

Check out our live demo or download a copy of the project source code to run on your own server. This is the best infinite page scroll solution for dynamic websites which are not powered by a CMS.

Final Thoughts

I do hope this tutorial may be educational and will open the doors for new infinite loading effects. Web designers have been vigilant about presenting new trends in a uniform and coherent fashion. This means users are becoming more accustomed to infinite scroll within their daily interactions. It is up to designers & developers to keep up with these trends and see how they may apply onto ideas in the future.

Please feel free to download a copy of both demos we have presented in the article. Each of their respective HTML pages are constructed using very minimalist code, which makes it easier to copy and implement on your own. But there are additional parameters to each function that may be of interest for developers. Be sure to toy around with the codes on your own and let us know your thoughts in the post discussion area.

No comments:

Post a Comment