Pagination with numbers is, in many ways, counter intuitive and time consuming for the user. They have to stop, click on a number, wait for the page to load, and then continue their search. Some websites such as facebook have opted out of this notion of pagination for a system which loads content automatically as the user scrolls. In this tutorial that is what we’re going to be making.
How it works
I’ve created a little plugin that allows us to accomplish our goal. Simply put the plugin checks if the user is at the bottom of the container you specify and loads more content accordingly. Then this data is sent to an ajax file which processes what posts to show.
// Check the user is at the bottom of the element if($(window).scrollTop() + $(window).height() > $this.height() && !busy) { // Now we are working, so busy is true busy = true; // Tell the user we're loading posts $this.find('.loading-bar').html('Loading Posts'); // Run the function to fetch the data inside a delay // This is useful if you have content in a footer you // want the user to see. setTimeout(function() { // This is the Ajax function getData(); }, $settings.delay); }
The key line here is if($(window).scrollTop() + $(window).height() > $this.height() ..
. This is basically saying, if the user scroll position is greater than the height of the element targeted, then more elements should be loaded.
What is Ajax?
Ajax is how we send data to files when an event happens in javascript. For example, when we scroll we want to send some data to another file to figure out what to do. That file is usually a PHP file which will process the data sent, and then you can do something like grab information from a database. So how do we do this with jQuery? Since we’re posting data, we use the $.post
function. It looks a little like this:
$.post('file.php', { information : 'to be sent', to : 'file' }, function(data) { } });
So in the above example we end the information (thats the bit inside the first set of curly brackets) to the file, file.php. When the information is sent it will return some information in the form of a data variable, and we can then use that data to return information to the user via Javascript.
The ajax file
The ajax file is going to have to be customized to fit your needs. All you have to do is grab some information from the MySQL database of your choice with some PHP. I have created a very basic ajax.php file that grabs information from a wordpress MySQL database and displays the content with the title and link. It looks a little like this, but it will be included with the download files in the download link above.
<?php mysql_connect('localhost', 'username', 'password') or die(); mysql_select_db('database'); $offset = is_numeric($_POST['offset']) ? $_POST['offset'] : die(); $postnumbers = is_numeric($_POST['number']) ? $_POST['number'] : die(); $run = mysql_query("SELECT * FROM wp_posts WHERE post_status = 'publish' AND post_type ='post' ORDER BY id DESC LIMIT ".$postnumbers." OFFSET ".$offset); while($row = mysql_fetch_array($run)) { $content = substr(strip_tags($row['post_content']), 0, 500); echo '<h1><a href="'.$row['guid'].'">'.$row['post_title'].'</a></h1><hr />'; echo '<p>'.$content.'...</p><hr />'; } ?>
Using the Plugin
Once you have your ajax file sorted out, its just a case of running the plugin. There are a bunch of variables you can determine, but it’s important that you define the query if you’re using the original ajax.php file listed above.
To run the plugin just upload all the files and create a container in your HTML called #content
or whatever you want to call your container. Then run the plugin on that. Easy!
$(document).ready(function() { $('#content').scrollPagination({ nop : 10, // The number of posts per scroll to be loaded offset : 0, // Initial offset, begins at 0 in this case error : 'No More Posts!', // When the user reaches the end this is the message that is // displayed. You can change this if you want. delay : 500, // When you scroll down the posts will load after a delayed amount of time. // This is mainly for usability concerns. You can alter this as you see fit scroll : true // The main bit, if set to false posts will not load as the user scrolls. // but will still load if the user clicks. }); });
In the download you’ll find the files necessary to do everything I’ve shown you. Since I can’t include database details you will have to supply your own which you can edit in the ajax.php file. And that’s it! Have a good day!
Comments
Great post, that will be useful to try out. Question for you – similar to this, have you seen or implemented a way to swipe WordPress pages (through the prev / next loop of a custom post type) left / right on mobile devices? It’s not the infinite scroll, it would have to stop on each page to view, but a similar process possibly?
Thanks, J
I am actually working on something like this at the minute, hopefully if it works correctly (I’m trying to work on a way to make it work on desktop too), I’ll be able to post it soon!
That’s awesome – thanks for sharing, great stuff.
Hi Johnny, just curious if you were able to code up a way to swipe through WordPress pages? The infinite scroll works great.
Thanks,
Jonathon
its really awesome article i was searching for it thank you and keep going :)
Hi, this is an awesome work. Congratulations. But I’m having a problem. How can you hide the load more button on the last query or just when there’s no more content to display. I hope you can help me. Sorry for my english, I speak spanish.
Hey Luis, first off, open up the Javascript file, and around line 53 you will see a little bit of code like this:
Change this line (line 54):
to this:
I hope this helps :)
Hey, Jhonny, this works almost great. But, the load more button should hide right after the last query result. If there’s no more content loading it shouldn’t display anything else. I hope you understand me. It’s important for user expectations.
Hello Johnny Simplson, does not work in IE? how to get crossbrowser?
It doesn’t work in IE? What version? I’ll test it out later.
Hi there,
I am the assistant editor of Appliness digital magazine (appliness.com/download) for web developers. This post would be a great fit for our readers and I wanted to see if we could use in in the Feb. issue? We would include your headshot, link to your website, twitter account, github, etc.
If so, or if you have any questions, please email me :)
Cheers,
Maile Valentine
What is the implications with SEO? Would you suggest having a full back as when i view the source of my page all i get is:
Thanks
Ross
how can we use it in wordpress
At a first start or load no scrollbar is visible, due to the limited number of text or messages loaded. The only way to load the remaining items is by clicking. After a while the scrollbar is there and then remaining items can be loaded by scrolling. Is there a way to load items till a scrollbar is shown on the page?
How To get Scrollbar height??? using jquery or javascript?
How To get Scrollbar height??? using jquery or javascript..
Hello, I have a doubt, works in IE7?
Hi,
It can be used on the same page twice?
Yes you can do.use different id for different div.It wil work.
I am using scroll in my website. By default it will display all the post. But I want to put search functionality in my website so is it possible to send extra parameters to the ajax.php page so that I can filter data in ajax.php page and display it on front instead of default posts ?
Thanks in advance
Hi, this is an awesome work. But I’m having a problem.While fetching data from database some times same data is repeating more times.Can any one help me out with this issue..
Thanks in advance
Did you change the script at all? I haven’t run into this problem but I imagine it’s because the getData() function is firing more than once. What browser are you using?
Great plugin! I have a problem running it with masonry. Your plugin work’s great, but masonry stopped working. You have any ideea why and what i can do?
I’m facing same issue (using Chrome).
Maybe it happens when we try to scroll too fast, and I guess it’s because the ajax post function runs async.
So, for some reason, the var “busy” it’s not doing its job.
I’m trying to figure out a workaround for that.
Have you guys had any luck with masonry? I’m also struggling still..
I resolved the previous issue..This is the best script i found on infinite scroll great work..Till now i don’t have problems with this..could you help me out in customizing this script such that for example when we scroll down to the bottom of the page after loading all posts,we have a link for the post when we click it it goes to another page.when we click on browser back button can we load all posts which already loaded and go to the location were the post has clicked?
This is the best script I found searching on google. Great work Keep it up.
Your style is so unique in comparison to other folks I’ve read stuff from. Thank you for posting when you have the opportunity, Guess I’ll just book mark this site.
Thanks for the wonderful script and the explaination!
Great plugin and by far the most simple one that I’ve come across.
I’m also having an issue with getting it to work with masonry.
Any tips on getting this to work alongside masonry?
After looking at masonry and the code the problem seems to arise from the fact that the data is appended and masonry cannot access this data since it’s not reading the DOM in the updated form.
Hello, Great job, but it’s no working for me, for exemple:
here are all posts, fetched ‘one page’:
title 1
description
comments(12)
—————-
title2
description
comments(4)
—————–
title3
description
comments (47)
—————–
i would like to use it to load comments, like facebook, the problem here, it works only for the last result, i mean title3.
i modified it “from ID to class” but samething, may you help please ?
Hi, I have some problems with this. Infinite Scroll is working but on loaded data other scripts don’t work, shadowbox for example. This problems can be solved ?
Check the error console and see what it says in dev tools
Resource interpreted as Document but transferret with MIME type application/x-shockwave-flash
also on voting buttons don’t send any data to database…
(I’m not using any platform like wordpress, joomla, etc…)
I cant think what amount of the I simply wasnt conscious of. Thank you for bringing more info with this topic personally.
can not use it with latest jquery … ?
Thank you!
It is working now ;)
Regards
Doesn’t seem to work in IE9 or IE10? Not totally sure but it seems like some issue with the POST data? When my results should be done it starts pulling in other information, as if the data parameters hadn’t been set. Great plugin though!
It works for me in IE8 and above! Are you sure you’re using the plugin right? Check out the demo page, you’ll see it works fine in IE8 (according to Browser Stack)
excuseme… how to create the sql file? whats is the structure?
It can be any structure you wish assuming you change the PHP file. If you read the rows I’ve set out in the PHP file you’ll see the names of columns etc that you can use.
Hi, Working perfectly for index page, but not working on url rewrited pages. Please suggest a solution
Hey when I use this for my user pages it keeps saying offset variable is undefined. What’s up with that?
[Notice: Undefined index: offset in C:\xampp\*####*\ajax.php on line 6]
Thank you SO much for sharing this! Very, very useful.
Hi Johnny,
Awesome post – got it working no problem so thanks for that. I’m using it on wordpress and have a question about extending the functionality.
Essentially i’ve got a wordpress page with three columns, each column is for a different query – so column a loads posts with tag 1, column 2 loads posts with tag 2 and column 3 loads posts with tag 3.
I’ve got the plugin working for one of the columns, but how can i get it working for the other two columns on the page too – independently of each other.
Ben.
this source that you made is perfect I’d ever seen.it’s really clear and simplistic. I made mobile version by using this source. the only problem I have is, first loading is little bit slow. and sometimes it doesn’t work. Then, when it is loaded initmessage button show up on the top and disapper. I want to solve two problems. first thing is I want to make first loading faster. second is I want to remove initmessage button. please let me know. I really appreciate it.
hello I give you php code to their own ,sent js with code it will by suitable?
“other translation”
I give you php codes, You are the codes JS code to conform. Is it possible?
——————————–
“Grammatical errors can be”
language translate – translate.google.com
Hello, have some form of the typing END and go to the bottom of the page to make it stop scrolling and then charge only become visible when loading a div? Thank you!
Hi Johnny,
I just tested your demo page using mobile safari, it does not auto load.
Anyway good jobs!!
http://www.codetrip.info/codetrip/169/PHP/Perfect-PHP-Pagination-Script-With-Live-Demo
Perfect PHP Pagination Script With Live Demo
The data repeates after loading. It shows my data but repeats it again. pls help
Thanks for a great script. By default it will display all the post. But I want to put search functionality in my website so is it possible to send extra parameters to the ajax.php page so that I can filter data in ajax.php page and display it on front instead of default posts ?
Will be VERY thankful for an example.
Thanks in advance
Hi, great script.
I have the same problem with extra parameters filtering in ajax.php
I use GET method to get an item’s ID and then pass it in the query.
But it does not pass into ajax.php in anyway. How can I do this?
I tried putting
$.post(‘ajax.php’+window.location.search, …
in javascript.js but no results.
Could you please give me instructions on how to pass the GET variable to ajax.php (the mysql query)?
Thanks.
This script is very good, but not working in IE10.
Hi,
I am trying to use this plug-in for phones (iPhone & Android phones). In Android phone “scroll” event not being fired when user swipes on device. Could you please suggest? Thanks in advance.
i try it with SQL Server 2008 and it work very fine :)
i have a question about the possibility to start showing data just after searching in database (after buton clic for exemple)?
many thanks
Mehdi
Hello Johnny Congratualtions, the script is nice, but i have some problem working witj IE,
I see an error like this:
Notice: Undefined index: offset in D:\www\africa60\load_news.php on line 55
Can you help me to solve problem for IE
Now I’m using IE9 but not work
Thank you
This would be really cool if it was ported to a wordpress plugin. I’m tired of native pagination, and besides more of the time we no index it anyway.
Urgent someone to help me …
Within the scroll.php I have a link that is
and the index I have the following:
$ (document). ready (function () {
$ (“. curtir_coracao_amizades”). click (function () {
alert (“Heart clicked”);
});
});
But I can not make it work at all, he can not call anything in jquery that this was the same file, can someone help me please
Please could you help me? I will repeat my post. the first time you load it loads fine then 1 time 2 times 4 times and then multiplying so this is the url http://salmarina.cleteci.com/recetas/
Great work !!!
I used this script in a show result page. It is working fine. But I am getting some problem when it comes to search filter using ajax.
What I need is to restart the pagination on #content div on a particular condition of jquery.
I will highly appreciate if you can sort it out.
Thanks in advance
This script works great.
However I have a question. How would you setup url parameters with this script? I would like to use multiple queries for different pages throughout a website. I would like to know how you would do that?
Thanks.
Hi there,
Great script. I only have 2 issues.
1. As someone mentioned above about hiding the scroll button if no posts are loaded. Your solution $this.find(‘.loading-bar’).hide(); doesn’t seem to work.
2. Every time I refresh a page that has the infinite scrolling, the scroll button flashes very quickly at the top of the body and then back to original place.
Aside from these two minor issues, you have done a great job with the script. Thank you!
i use this script ->
I thought this is a bug ->
When i scroll just on page load ->
they show my posts 2 times.
means pageload and scroll call on same time
Thanks
Nicely explained article.. thanks for sharing.