Advertisement

Create a Twitter-Like "Load More" Widget

by
Gift

Start a hosting plan from $3.92/mo and get a free year on Tuts+ (normally $180)

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 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.

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:

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.

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

Load 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.

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:

Sample 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.

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.

AJAX 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:

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.

Initial 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.

Scrolls

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

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.

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...

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..."....

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...

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

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

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!

AJAX JSON

MooTools Complete Code

jQuery Version

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

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