Pages

Wednesday, June 26, 2013

Create an Infinite Scrolling Gallery, Content


Pagination is a technique used to break large data sets into small blocks in order to reduce the server load. We used to create pagination buttons with page numbers and next/previous links. Now pagination has gained a new perspective with infinite scrolling.
Are you new to infinite scrolling? Then take a quick look at the demo before we start.

What is Infinite Scrolling

Infinite scrolling is where you can keep scrolling and data will keep coming until all the data is displayed. In this technique, the first set of data will be displayed initially. Once you scroll to the end of the window the next page of data will be generated and so on. No pagination buttons are required and you get the data on demand. Let’s see how we can create infinite scrolling.

What are we going to do?

We are going to create an infinite scrolling page with images, similar to Pinterest. These are the requirements needed before we start coding.
How to Create an Infinite Scrolling Gallery in 10 Minutes

  • Initial data set should be loaded on page load.
  • Once the scrollbar reaches the end of the window the next page of data should be displayed.
  • When we are close to the end of a page, message should be displayed mentioning “Loading More Content”.
  • Once all the data is generated, message should be displayed as “No More Content”.

Generating the Initial Data Set

When the page is loaded we have to get the data from the database and display the initial result. I have stored the names of the images in a database table. I have simplified the code using basic syntax so that beginners can go through the tutorial without any problems.
1<!--?php $con = mysql_connect("localhost""username","password"); mysql_select_db("database_name"); $result = mysql_query("select SQL_CALC_FOUND_ROWS * from scroll_images order by id asc limit 12"); $row_object = mysql_query("Select Found_Rows() as rowcount");$row_object = mysql_fetch_object($row_object);$actual_row_count $row_object--->rowcount;
2
3?>
The result will be broken into pages of 12 images. So the above code generates the first 12 results from the database table. Also keep in mind that $actual_row_count variable will hold the total number of images available in the table.
So lets move onto creating the initial version of our HTML document.
1        Infinite Scroll
2<script type="text/javascript" src="jquery-1.7.2.js"></script></pre>
3<div id="more">Loading More Content</div>
4<pre>
5
6</pre>
7<div id="no-more">No More Content</div>
8<pre>
9
10</pre>
11<div id="result"></div>
12<pre>
13"; } ?> 
I have included jQuery and some sample CSS code to style our page at the top. In the body section you can see 2 div elements called more and no-more. These are used to show the status when we keep scrolling and position of these divs are made fixed. Next we are going to display the images inside the PHP code using the results we generated earlier. So the initial data set is displayed now and we have to create the scrolling part.

Paginating Data Using Scrolling

Let’s add the jQuery scrolling event to our page. jQuery provides a built-in function called scroll as shown in the code below.
1$(window).scroll(function () {
2
3});
Whenever you scroll to the top or bottom, the code inside this function will be executed.Identify end of the Page We are loading the next set of data, once the scroll reaches the end of the page. So first we have to identify the end of the page. Now I’ll show you a simple technique for that.
How to Create an Infinite Scrolling Gallery in 10 Minutes

1if($(window).scrollTop() + $(window).height() == $(document).height()) {
2
3}
jQuery scrollTop function will return the area hidden on the top of your page. $(window).height() gives the height of the browser viewport. So addition of both values will be equal to the page height, when scroll reaches the bottom. Pretty simple isn’t it? Now we got the basics covered and we can move onto the full script code as shown below.
1<script type="text/javascript">// <![CDATA[
2             var page = 1;             $(window).scroll(function () {                 $('#more').hide();                 $('#no-more').hide();                 if($(window).scrollTop() + $(window).height() > $(document).height() - 200) {
3                    $('#more').css("top","400");
4                    $('#more').show();
5                }
6                if($(window).scrollTop() + $(window).height() == $(document).height()) {
7
8                    $('#more').hide();
9                    $('#no-more').hide();
10
11                    page++;
12
13                    var data = {
14                        page_num: page
15                    };
16
17                    var actual_count = "<?php echo $actual_row_count; ?>";
18
19                    if((page-1)* 12 > actual_count){
20                        $('#no-more').css("top","400");
21                        $('#no-more').show();
22                    }else{
23
24                    }
25
26                }
27
28            });
29// ]]></script>
Code Explanation
  • First we define the variable to hold the current page number. Initially it will be 1.
  • Message boxes are made hidden at the beginning of scroll.
  • Next you can see the if statement which I didn’t explain earlier. We have to show the message “Loading More Content” just before the scroll reaches end. I have defined it to be displayed 200px before the end of document.
  • Then inside the if statement used to identify bottom of page, page number is increased by one and the total data count is stored.
  • Then simple calculation is done to check whether total results are displayed. If so we show the message “No More Content”.
  • Now it’s time to generate the next page, which I will be explaining in the next section.
Requesting Data for Next Page
We have to use an Ajax call to request the next page from server as shown below. This code should be inside the else part we left empty in the earlier code.

1$.ajax({
2    type: "POST",
3    url: "data.php",
4    data:data,
5    success: function(res) {
6        $("#result").append(res);
7    }
8});
Creating Page for Data Generation
We need a separate PHP file to request the Ajax request data. I have created a file called data.php to generate results as shown below.
1<!--?php <br ?-->$requested_page $_POST['page_num'];
2$set_limit = (($requested_page - 1) * 12) . ",12";
3
4$con = mysql_connect("localhost""username","password");
5mysql_select_db("database_name");
6
7$result = mysql_query("select  * from scroll_images order by id asc limit $set_limit");
8
9$html '';
10
11while ($row = mysql_fetch_array($result)) {
12$html .= "</pre>
13<div><img src="images/&quot; . $row[" alt="" name="" /></div>
14<pre>
15";
16}
17
18echo $html;
19exit;
20?>
We are done with creating the infinite scrolling pagination. Let’s have a look at how it is used in popular websites

No comments:

Post a Comment