Advertisement
  1. Code
  2. Web Development

Create a Twitter-Like "Load More" Widget

Scroll to top
Read Time: 13 min

Both Twitter and the Apple App Store use a brilliant technique for loading more information; you click the link and fresh items magically appear on the screen. This tutorial teaches you to use AJAX, CSS, Javascript, JSON, PHP, and HTML to create that magic. This tutorial will also feature both jQuery and MooTools versions of the script.


Assumptions

There are a few assumptions and notes that we're going into this system with:

  • The server needs to be running PHP5 so that we can use PHP5's JSON functions.
  • We'll be pulling database records from a WordPress "posts" MySQL table. What's great about the code provided is that you may use it with any database system; all you'll need to do is modify the MySQL query and the JSON properties used by jQuery or MooTools.
  • The client must support javascript.
  • We're using MooTools 1.2.3 Core and More 1.2.3.1. If jQuery is the preferred framework, jQuery 1.3.2 and Ariel Flesler's ScrollTo plugin.

This tutorial will feature an explanation of the MooTools javascript. While jQuery's
syntax differs from MooTools, the beauty in modern javascript frameworks is that
they differ mainly in syntax, not in logic. The jQuery javascript will be provided below.

The Plot

Here's the sequence of events that will take place in our slick widget:

  • The page loads normally with an initial amount of posts showing
  • The user clicks the "Load More" element at the bottom of the list
  • An AJAX/JSON request will fire, retrieving a specified amount of new posts
  • Our jQuery/MooTools javascript will receive the result and build a series of new HTML elements containing the JSON's information
  • Each element will slide into the widget's container element
  • Once all of the elements have been loaded into the page, the window will scroll down to the first new item
  • Rinse and repeat.

Load More WidgetLoad More WidgetLoad More Widget

Step One: The PHP/MySQL

The first step is deciding how many posts need to be loaded during the initial page load. Since our widget will remember how many posts were loaded during the last load (in case a user visits another page and comes back), we'll need to use the session.

1
2
	/* settings */
3
	session_start();
4
	$number_of_posts = 5; //5 posts will load at a time

5
	$_SESSION['posts_start'] = $_SESSION['posts_start'] ? $_SESSION['posts_start'] : $number_of_posts; //where we should start

The above code snippet contains all the "settings" content that we need. Next we need to create a PHP function that connects to our database, grabs more records, and returns their contents in JSON format:

1
2
	/* grab stuff */
3
	function get_posts($start = 0, $number_of_posts = 5) {
4
		/* connect to and select the db */
5
		$connection = mysql_connect('localhost','username','password'); //hostname, username, password

6
		mysql_select_db('davidwalsh83_blog',$connection);
7
		/* create the posts array */
8
		$posts = array();
9
		/* get the posts */
10
		$query = "SELECT post_title, post_content, post_name, ID FROM wp_posts WHERE post_status = 'publish' ORDER BY post_date DESC LIMIT $start,$number_of_posts";
11
		$result = mysql_query($query);
12
		/* for every post... */
13
		while($row = mysql_fetch_assoc($result)) {
14
			/* set the post content equal to the first paragraph...a "preview" regular expression */
15
			preg_match("/<p>(.*)<\/p>/",$row['post_content'],$matches);
16
			$row['post_content'] = strip_tags($matches[1]);
17
			/* add this record to the posts array */
18
			$posts[] = $row;
19
		}
20
		/* return the posts in the JSON format */
21
		return json_encode($posts);
22
	}

The above PHP contains a very simple regular expression that grabs the first paragraph of my post's content. Since the first paragraph of most blog posts serves as a introduction to the rest of the content, we can assume that paragraph will server as a nice preview of the post.

Once the above function is ready, we need to create our AJAX request listener. We'll know that someone has sent an AJAX request if the $_GET['start'] variable is set in the request URL.
If a request is sensed, we grab 5 more posts via our get_posts() function and echo their JSON out. Once we've output the new posts in JSON format, we save the number of items that the user has requested and kill the script, as seen below.

1
2
/* loading of stuff */
3
if(isset($_GET['start'])) {
4
	/* spit out the posts within the desired range */
5
	echo get_posts($_GET['start'],$_GET['desiredPosts']);
6
	/* save the user's "spot", so to speak */
7
	$_SESSION['posts_start']+= $_GET['desiredPosts'];
8
	/* kill the page */
9
	die();
10
}

That concludes the server-side code for our widget. Simple, no?

Load More WidgetLoad More WidgetLoad More Widget

Step 2: The HTML

There's not much raw HTML to this widget initially. We'll create one main widget container. Inside the widget container will be a posts wrapper and our "Load More" element which will server as a virtual like to trigger the loading of more content.

1
2
<!-- Widget HTML Starts Here -->
3
<div id="posts-container">
4
	<!-- Posts go inside this DIV -->
5
	<div id="posts"></div>
6
	<!-- Load More "Link" -->
7
	<div id="load-more">Load More</div>
8
</div>
9
<!-- Widget HTML Ends Here -->

Though we don't insert individual post elements yet, it's important to know the HTML structure of post DIV elements that will be injected into the posts wrapper:

1
2
<div class="post">
3
	<a href="{postURL}" class="post-title">{post_title}</a>
4
	<p class="post-content">
5
		{post_content}
6
		<br />
7
		<a href="{postURL}" class="post-more">Read more...</a>
8
	</p>
9
</div>

Sample ItemSample ItemSample Item

Step 3: The CSS

Time to add some flare to our widget. Feel free to format the widget's elements any way you'd like. I've chosen to add my caricature on the left and the post title, content, and link to the right. We'll need to add CSS for the static HTML elements and the javascript-generated elements as show below.

1
2
#posts-container			{ width:400px; border:1px solid #ccc; -webkit-border-radius:10px; -moz-border-radius:10px; }
3
.post						{ padding:5px 10px 5px 100px; min-height:65px; border-bottom:1px solid #ccc; background:url(dwloadmore.png) 5px 5px no-repeat; cursor:pointer;  }
4
.post:hover					{ background-color:lightblue; }
5
a.post-title 				{ font-weight:bold; font-size:12px; text-decoration:none; }
6
a.post-title:hover			{ text-decoration:underline; color:#900; }
7
a.post-more					{ color:#900; }
8
p.post-content				{ font-size:10px; line-height:17px; padding-bottom:0; }
9
#load-more					{ background-color:#eee; color:#999; font-weight:bold; text-align:center; padding:10px 0; cursor:pointer; }
10
#load-more:hover			{ color:#666; }

One extra CSS class we'll create is called "activate", which we'll show whenever an AJAX request starts and hide when the request completes.

1
2
.activate					{ background:url(/dw-content/loadmorespinner.gif) 140px 9px no-repeat #eee; }

AJAX SpinnerAJAX SpinnerAJAX Spinner

Step 4: The MooTools Javascript

Our MooTools javascript will make the magic happen. We'll use a closure pattern to contain the MooTools code as a best practice:

1
2
//safety closure

3
(function($) {
4
	//when the DOM is ready...

5
	window.addEvent('domready,function() {

6
		

7
		/* ALL JAVASCRIPT WILL BE IN HERE */

8
		

9
	});

10
})(document.id);

Once the DOM is ready, we provide the initial javascript settings. Note that one of those settings, initialPosts, contains the JSON for the first batch of posts that should show when the page loads. We also define variables for how many posts we load initially and the number of posts to grab during each AJAX request.

1
2
//settings on top

3
var domain = 'http://davidwalsh.name/'; //your domain or directory path goes here

4
var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
5
var start = <php echo $_SESSION['posts_start']; ?>;
6
var desiredPosts = <?php echo $number_of_posts; ?>;

Initial JSONInitial JSONInitial JSON

Once our settings are in place, we define a function to handle the JSON we receive at page load as well as via future AJAX requests. For every post in the JSON, we...

  • Create a post URL variable which we'll use a bit later in the loop
  • Create a DIV "post" element which will contain the post title, content, and link (in the format shown above)
  • Inject the newly created "post" element into the posts wrapper
  • Create a Fx.Slide object for the new "post" element so we can hide the element instantly, then slide it into view
  • Scroll the window down to the first newly-injected post

Here's the MooTools javascript code that gets it done.

1
2
//function that creates the posts

3
var postHandler = function(postsJSON) {
4
	postsJSON.each(function(post,i) {
5
		//post url

6
		var postURL = '' + domain + post.post_name;
7
		//create the HTML "post" element

8
		var postDiv = new Element('div',{
9
			'class': 'post',
10
			events: {
11
				//click event that makes the entire DIV clickable

12
				click: function() {
13
					window.location = postURL;
14
				}
15
			},
16
			id: 'post-' + post.ID,
17
			html: '<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>'
18
		});
19
		//inject into the container

20
		postDiv.inject($('posts'));
21
		//create the Fx Slider

22
		var fx = new Fx.Slide(postDiv).hide().slideIn();
23
		//scroll to first NEW item

24
		if(i == 0) {
25
			var scroll = function() {
26
				new Fx.Scroll(window).toElement($('post-' + post.ID));
27
			};
28
			scroll.delay(300); //give time so scrolling can happen

29
		}
30
	});
31
};

ScrollsScrollsScrolls

Now that our postHandler function is defined, it's time to handle the initial JSON string of elements.

1
2
//place the initial posts in the page

3
postHandler(initialPosts);

Next we create a few more variables to store the value of our AJAX request and hold the values of the PHP session's start value, the number of posts to grab at a time, and the "Load More" element.

1
2
var start = <?php echo $_SESSION['posts_start']; ?>;
3
var desiredPosts = <?php echo $number_of_posts; ?>;
4
var loadMore = $('load-more');

To cut down on memory usage, we'll create our Request.JSON object outside of the click event we'll soon add. The Request.JSON object looks long but it's really quite simple. Breaking it down...

We create the request object with basic settings...

1
2
	var request = new Request.JSON({
3
		url: 'load-more.php', //ajax script -- same script

4
		method: 'get',
5
		link: 'cancel',
6
		noCache: true,
7
		//more settings coming...

Add an onRequest parameter that adds our "activate" CSS class to the "Load More" clickable element and change the "Load More" element's text to "Loading..."....

1
2
onRequest: function() {
3
	//add the activate class and change the message

4
	loadMore.addClass('activate').set('text','Loading...');
5
},

Add an onSuccess parameter that resets the "Load More" element text, keeps track of the current start spot for grabbing future elements, and handle the JSON response the same way we did with the initial posts...

1
2
onSuccess: function(responseJSON) {
3
	//reset the message

4
	loadMore.set('text','Load More');
5
	//increment the current status

6
	start += desiredPosts;
7
	//add in the new posts

8
	postHandler(responseJSON);
9
},

Add an onFailure function to update the "LoadMore" text upon failure...

1
2
onFailure: function() {
3
	//reset the message

4
	loadMore.set('text','Oops! Try Again.');
5
},

Lastly, add an onComplete function that removes the spinner once the request is complete, regardless of success or failure.

1
2
onComplete: function() {
3
	//remove the spinner

4
	loadMore.removeClass('activate');
5
}

The last step is adding the click event to "Load More" element. Upon click we make the AJAX request and all of the work above gets triggered. Success!

1
2
//add the "Load More" click event

3
loadMore.addEvent('click',function(){
4
	//begin the ajax attempt

5
	request.send({
6
		data: {
7
			'start': start,
8
			'desiredPosts': desiredPosts
9
		},
10
	});
11
});

AJAX JSONAJAX JSONAJAX JSON

MooTools Complete Code

1
2
	//safety closure

3
	(function($) {
4
		//domready event

5
		window.addEvent('domready',function() {
6
			//settings on top

7
			var domain = 'http://davidwalsh.name/';
8
			var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']);  ?>;
9
10
			//function that creates the posts

11
			var postHandler = function(postsJSON) {
12
				postsJSON.each(function(post,i) {
13
					//post url

14
					var postURL = '' + domain + post.post_name;
15
					//create the HTML

16
					var postDiv = new Element('div',{
17
						'class': 'post',
18
						events: {
19
							click: function() {
20
								window.location = postURL;
21
							}
22
						},
23
						id: 'post-' + post.ID,
24
						html: '<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>'
25
					});
26
					//inject into the container

27
					postDiv.inject($('posts'));
28
					//create the Fx Slider

29
					var fx = new Fx.Slide(postDiv).hide().slideIn();
30
					//scroll to first NEW item

31
					if(i == 0) {
32
						var scroll = function() {
33
							new Fx.Scroll(window).toElement($('post-' + post.ID));
34
						};
35
						scroll.delay(300); //give time so scrolling can happen

36
					}
37
				});
38
			};
39
40
			//place the initial posts in the page

41
			postHandler(initialPosts);
42
43
			//a few more variables

44
			var start = <?php echo $_SESSION['posts_start']; ?>;
45
			var desiredPosts = <?php echo $number_of_posts; ?>;
46
			var loadMore = $('load-more');
47
			var request = new Request.JSON({
48
				url: 'load-more.php', //ajax script -- same page

49
				method: 'get',
50
				link: 'cancel',
51
				noCache: true,
52
				onRequest: function() {
53
					//add the activate class and change the message

54
					loadMore.addClass('activate').set('text','Loading...');
55
				},
56
				onSuccess: function(responseJSON) {
57
					//reset the message

58
					loadMore.set('text','Load More');
59
					//increment the current status

60
					start += desiredPosts;
61
					//add in the new posts

62
					postHandler(responseJSON);
63
				},
64
				onFailure: function() {
65
					//reset the message

66
					loadMore.set('text','Oops! Try Again.');
67
				},
68
				onComplete: function() {
69
					//remove the spinner

70
					loadMore.removeClass('activate');
71
				}
72
			});
73
			//add the "Load More" click event

74
			loadMore.addEvent('click',function(){
75
				//begin the ajax attempt

76
				request.send({
77
					data: {
78
						'start': start,
79
						'desiredPosts': desiredPosts
80
					},
81
				});
82
			});
83
		});
84
	})(document.id);

jQuery Version

If you prefer the jQuery javascript framework, it's your lucky day; here's the jQuery version:

1
2
	//when the DOM is ready

3
	$(document).ready(function(){
4
		//settings on top

5
		var domain = 'http://davidwalsh.name/';
6
		var initialPosts = <?php echo get_posts(0,$_SESSION['posts_start']); ?>;
7
		//function that creates posts

8
		var postHandler = function(postsJSON) {
9
			$.each(postsJSON,function(i,post) {
10
				//post url

11
				var postURL = '' + domain + post.post_name;
12
				var id = 'post-' + post.ID;
13
				//create the HTML

14
				$('<div></div>')
15
				.addClass('post')
16
				.attr('id',id)
17
				//generate the HTML

18
				.html('<a href="' + postURL + '" class="post-title">' + post.post_title + '</a><p class="post-content">' + post.post_content + '<br /><a href="' + postURL + '" class="post-more">Read more...</a></p>')
19
				.click(function() {
20
					window.location = postURL;
21
				})
22
				//inject into the container

23
				.appendTo($('#posts'))
24
				.hide()
25
				.slideDown(250,function() {
26
					if(i == 0) {
27
						$.scrollTo($('div#' + id));
28
					}
29
				});
30
			});	
31
		};
32
		//place the initial posts in the page

33
		postHandler(initialPosts);
34
		//first, take care of the "load more"

35
		//when someone clicks on the "load more" DIV

36
		var start = <?php echo $_SESSION['posts_start']; ?>;
37
		var desiredPosts = <?php echo $number_of_posts; ?>;
38
		var loadMore = $('#load-more');
39
		//load event / ajax

40
		loadMore.click(function(){
41
			//add the activate class and change the message

42
			loadMore.addClass('activate').text('Loading...');
43
			//begin the ajax attempt

44
			$.ajax({
45
				url: 'load-more.php',
46
				data: {
47
					'start': start,
48
					'desiredPosts': desiredPosts
49
				},
50
				type: 'get',
51
				dataType: 'json',
52
				cache: false,
53
				success: function(responseJSON) {
54
					//reset the message

55
					loadMore.text('Load More');
56
					//increment the current status

57
					start += desiredPosts;
58
					//add in the new posts

59
					postHandler(responseJSON);
60
				},
61
				//failure class

62
				error: function() {
63
					//reset the message

64
					loadMore.text('Oops! Try Again.');
65
				},
66
				//complete event

67
				complete: function() {
68
					//remove the spinner

69
					loadMore.removeClass('activate');
70
				}
71
			});
72
		});
73
	});

The MooTools and jQuery versions are exactly the same logic with different syntax!

Mission Accomplished!

Implementing this widget on your website is a great way to add dynamism and creativity to your website. I look forward to seeing your widget! Have questions suggestions for improvements? Post them below!


Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.