How to create easy pagination with jQuery

How to create easy pagination with jQuery

113 429020
How to create easy pagination with jQuery

How to create easy pagination with jQuery

jQuery pagination. All we know, that when we facing with necessarity to display large amount of data – we starting thinking about adding pagination. So we split all our content to several pages. And in this case – each page contain some part of our information. As usual this is server-side pagination, where we extracting necessary amount data from database for each page. But commonly, in case of small (or middle) data sets – we don`t need such pagination. And we can just use user-side pagination using javascript to manage with our pages. Today I will show you how to create such pagination.

Here are samples and downloadable package:

Live Demo

[sociallocker]

download in package

[/sociallocker]


Ok, download the source files and lets start coding !


Step 1. XHTML

Here are our main HTML file:

index.html (updated due few corrections)

<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/imtech_pager.js"></script>
<div class="example">
    <h3><a href="#">Paragraph pagination sample</a></h3>
    <div id="content">
        <div class="z">Sergey LUKYANENKO - The Boy and the Darkness - Chapter 1. The Sun Kitten.</div>
        <div class="z">Everything happened because I got ill.</div>
        <div class="z">It was already two in the afternoon, and I was lying in bed flicking through "Peter Pan" - I must have read it a hundred times over. I had long since pulled off the bandage my mother had tied around my neck in the morning, and thrown it into a corner. I simply can't understand - how can cotton wool soaked in vodka possibly help a cough? I don't argue with my mum, of course, but after she leaves I look after myself in my own way - namely, lie in bed with a book and wait for my germs to get tired of such a boring method of passing time. It usually helps - perhaps not at once, but after a day or three. A good thing, really, that the street outside looked quite miserable - the sun poking out for brief moments, only to make room for a patchy, nasty drizzle. Though, the sun never actually peeked into the room - our house is so unfortunately placed that it is in the shadows of the new nine-floor high-rises on every side. "The only use for such a flat is to grow mushrooms", - dad used to say, back when he still lived with us.</div>
        <div class="z">I put my book down on the floor next to the bed, and lay on my back. Perhaps, had I shut my eyes now, nothing would have happened. But there I was, lying staring at the ceiling and listening to the ticking of the clock in the hallway.</div>
        <div class="z">And a speck of sunlight jumped into the room through the glass. Small - the size of my hand - but surprisingly bright. As though the window was open, with bright summer sun outside. Someone was probably playing with a mirror on the balcony of the house across the street.</div>
        <div class="z">The rabbit floated across the ceiling, climbed down a wall, made a vase on the dressing-table glint, and stopped, shaking slightly, on my headrest.</div>
        <div class="z">- Don't go, - I said for some reason, knowing that in a moment the mirror would shift and the rabbit would leave my room forever. - Stay...</div>
        <div class="z">And that's when it all started.</div>
        <div class="z">The sun rabbit tore free of the bed and floated in the air. I didn't even realise at first that such things don't happen. It was only when the flat spot hanging in the air started puffing out to form a fuzzy orange ball that I understood - a miracle had happened.</div>
        <div class="z">Four paws stretched from orange glowing fur, followed by a tail and a head. Green cat eyes blinked and gazed at me steadily. And overall, in fact, the rabbit looked more like a kitten than anything else. Except he was hanging in the air, glowing, and seemed light as the fairy fluff that floats away if one blows gently.</div>
        <div class="z">- Hello, - purred the kitten. - Thank you for the invitation.</div>
        <div class="z">I closed my eyes for a second, but when I opened them again, the kitten hadn't disappeared. In fact, he'd flown closer.</div>
        <div class="z">- I don't believe in fairy tales, - I told myself. - I'm grown up now.</div>
        <div class="z">- Well, compared to the girl who was holding the True Mirror, you are quite grown up, - declared the kitten, unperturbed, and lowered himself onto the blanket. I glanced over - to see if there would be smoke - but everything seemed all right. I could feel warmth with my chest, but not strong. And the kitten tilted his head and added: - But one can't really call you adult, either. How old are you? Ten, maybe?</div>
        <div class="z">- Fourteen, - I replied, finding myself calming down at such a mundane question. - Who're you?</div>
        <div class="z">- A sun rabbit, - replied the kitten, examining himself curiously. - What an appearance.. do I look like one?</div>
        <div class="z">- <b>Like</b> what?</div>
        <div class="z">- Like a <p style="font-weight:bold;color:red;">sun</p> rabbit.</div>
        <div class="z">- More like a kitten.</div>
        <div class="z">- Hardly better, - stated the Kitten sadly and stretched out. And I didn't think of anything better than repeating:</div>
        <div class="z">- Who're you?</div>
        <div class="z">- But we have already arrived at a consensus! - said the Kitten with sudden hurt. - A sun rabbit, or more precisely - a kitten, because I look far more like one! What is there not to understand?</div>
        <div class="z">I found myself tongue-tied. Well, naturally, a small green animal that eats stones would simply be - a small green stone-eater. Simple. And a sun rabbit is a sun kitten, because he looks nothing like a rabbit.</div>
        <div class="z">- So you mean - any rabbit can come to life if one just calls it? - I asked cautiously. For some reason it seemed to me the Kitten would be hurt at the question again. But he just shook his head proudly:</div>
        <div class="z">- As if! Any! Only True Light, reflected in a True Mirror, can come to life.</div>
    </div>
    <div id="pagingControls"></div>
</div>
<script type="text/javascript">
var pager = new Imtech.Pager();
$(document).ready(function() {
    pager.paragraphsPerPage = 5; // set amount elements per page
    pager.pagingContainer = $('#content'); // set of main container
    pager.paragraphs = $('div.z', pager.pagingContainer); // set of required containers
    pager.showPage(1);
});
</script>

As you see – we put all content inside <div id="content"> element into P paragraphs. And than, using jQuery – doing small initialization of our pagination into prepared <div id="pagingControls"></div> element. Inside our initialization js script – you can see that I set our container element, name of paragraph tag, and amount paragraphs per page (5). All easy.

Update! I changed tag for paragraphs <p> to <div class="z"> for better selections. Now it able to handle with inline styles and tags

Step 2. CSS

Here are used CSS file. Just few styles for our demo:

css/styles.css

body{background:#eee;font-family:Verdana, Helvetica, Arial, sans-serif;margin:0;padding:0}
.example{background:#FFF;width:1000px;font-size:80%;border:1px #000 solid;margin:0.5em 10% 0.5em;padding:1em 2em 2em;-moz-border-radius:3px;-webkit-border-radius:3px}
#content p{text-indent:20px;text-align:justify;}
#pagingControls ul{display:inline;padding-left:0.5em}
#pagingControls li{display:inline;padding:0 0.5em}

Step 3. JS

Here are two JS files:

js/jquery.min.js

Both – just jQuery library. Available in package.

js/imtech_pager.js (updated due few corrections)

var Imtech = {};
Imtech.Pager = function() {
    this.paragraphsPerPage = 3;
    this.currentPage = 1;
    this.pagingControlsContainer = '#pagingControls';
    this.pagingContainerPath = '#content';
    this.numPages = function() {
        var numPages = 0;
        if (this.paragraphs != null && this.paragraphsPerPage != null) {
            numPages = Math.ceil(this.paragraphs.length / this.paragraphsPerPage);
        }
        return numPages;
    };
    this.showPage = function(page) {
        this.currentPage = page;
        var html = '';
        this.paragraphs.slice((page-1) * this.paragraphsPerPage,
            ((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
            html += '<div>' + $(this).html() + '</div>';
        });
        $(this.pagingContainerPath).html(html);
        renderControls(this.pagingControlsContainer, this.currentPage, this.numPages());
    }
    var renderControls = function(container, currentPage, numPages) {
        var pagingControls = 'Page: <ul>';
        for (var i = 1; i <= numPages; i++) {
            if (i != currentPage) {
                pagingControls += '<li><a href="#" onclick="pager.showPage(' + i + '); return false;">' + i + '</a></li>';
            } else {
                pagingControls += '<li>' + i + '</li>';
            }
        }
        pagingControls += '</ul>';
        $(container).html(pagingControls);
    }
}

Live Demo

Conclusion

I hope that today’s sample was pretty easy. And it will useful for your projects. Do not forget to say thank you :) Good luck!

SIMILAR ARTICLES


113 COMMENTS

  1. Same problem in IE 8/9. First page displays correctly, after that all pages are empty. Investigation shows every $(this).html is empty. In fact, (this.paragraphs)[i].innerHTML seems to be set to ” for every [i]. No js errors, just empty pages.

  2. Here is the problem:
    alert((this.paragraphs)[0].innerHTML);
    $(this.pagingContainerPath).html(html);
    alert((this.paragraphs)[0].innerHTML);

    In FF, the both alert box contents are the same. In IE, the second box is empty.

  3. Fixed it. In the set up section add the new line:
    pager.paragraphs = $(‘div.mainNewsItem’); // set of required containers
    items = $(‘div.mainNewsItem’).clone(); <– new
    pager.showPage(1);

    Then change:
    this.paragraphs.slice((page-1) * this.paragraphsPerPage,
    to:
    items.slice((page-1) * this.paragraphsPerPage,

    • Hello Lemuel,
      Thanks for your contribution in all your comments. I have been overloaded last weeks, was unable to answer before.

  4. One of the main roles of navigation is a page listing of items list. Product list, news, whatever… Imagine situation, when user clicked on some product in that list, to read detailed description of it. After reading as a general rule, a typical user clicks BACK button of his browser, to return to the products list for further navigation. And what hi gets? Right, hi gets FIRST page of navigation, but not the same one, with which he went to look for details about the selected product. But mast be!. While I can not find a suitable navigation system with jQuery usage, which would take into account this is a required parameter settings.

  5. hello and thanks for the script !
    I want to ask you how can i add a transition effect when a new page loads;

  6. I’m running into some issues with when you fire the showPage(); in IE7+ the entire content div goes blank. I’d love to pick your brain about that if you can shoot me an email :) This is ideally what i was looking for in a jQuery pagination. Thanks for the nice work.

    • Hello erhan,
      I’ve just test it with jQuery v1.6.1 (I don’t have version 1.5.1), and this pagination works well with 1.6.1

  7. Hi, I had a question. There seems to be an issue in IE in how it reads line 21 in imtech_pager.js. When you click to second page it cannot read the html() of the items. I believe it’s because IE reads the slice as slice(xy) as opposed to slice(x y) in other browsers…I may be way off on this. Any ideas or a fix? Great script!

    • Hello Libby,
      What version of your IE? I’ve just checked how this pagination works in IE9 – and, it works here.

  8. thanks dude woks like a charm, saves me rewriting the logic to do that every time i need pagination.

  9. How do i get the page to start from the top – article/para/line of the content once we click on page 2?

    • Hello Hitesh,
      What do you mean ‘from the top’ ?
      Whole text is already aligned from the top to the bottom

  10. Hello,

    Great tutorial but I like some other posters am having issues with this using older versions of jQuery. For those of us that work with older applications having it run on older versions would be great. I have it narrowed down to IE 7 and IE 8 not liking your JS when using older versions of jQuery. As an earlier poster said it is hiding the content divs. Is there a workaround for this? For example set your jQuery to be something like 1.3.2 and your browser to IE 8 at the minimum. Your code is by far the cleanest and easiest to use so I really don’t want to have to use another version that is out there. :(

    • Hello Aaron,
      Please pay attention that for our demo we use jquery.min.js (version 1.3.2) and, it works well with IE8, I’ve just tested it, re-check your side.

  11. hello admin,

    i am a trainee sotfware proffesional. i have been assigned a project Social Network.
    my index page is the page where viewer can see posts. 10 posts per page are allowed .and d posts should be with username .
    how to do that.
    regards ,
    vipin

    • Hello vipin,
      And, what’s problem with it? All you need is just prepare necessary HTML dom model of your posts (by users), then – you can apply our pagination script for your code.

  12. Hi Admin,

    I am looking for manual pagination with prev(button), manual input (text box), number of pages, next(Button). in javascript including jquery can you please provide me the required Code.

    Thanks
    Sandy

    • Hi Sandy,
      I don’t have a ready tutorial with pagination which has text box to put page number, but you can check our both tutorials about pagination

  13. Hello,
    the script works well, but I have a little problem. I’m using jQuery slideToggle and slideUp to show/hide divs on my page. When the site is loaded, on the first page everything works like a charm, slideToggle too. But when I choose another page, your script is working well, but the show/hide function stop working, even if I choose first page again. When I reload the site everything is OK again. It’s so strange and annoying… Any idea on this? :-)

  14. Hello , I’m a beginner in web developer , I found ur paging method is amazing , However when i use it on my web , it just show the paging number but the content still remains same. can give some guidance on my code ?

    <?php
    $branchID = $dBranches['BranchID'];
    $q2 = "SELECT * FROM my_image i, my_branch b WHERE b.branchID = i.branchID AND i.branchID = '".$dBranches['BranchID']."' ";
    $result2 = @mysqli_query($dbc, $q2);
    $imageData = mysqli_fetch_array($result2);
    echo ”.$dBranches[“BranchName”].”;
    echo ”;
    echo ”.$dBranches[“description”].”;
    ?>

    var pager = new Imtech.Pager();
    $(document).ready(function() {
    pager.paragraphsPerPage = 1; // set amount elements per page
    pager.pagingContainer = $(‘#show_company’); // set of main container
    pager.paragraphs = $(‘table’, pager.pagingContainer); // set of required containers
    pager.showPage(1);
    });

    • Hello Stephen,
      Sorry to say, but your code looks like a mess, there are several strange things: first – you messed HTML output with JS code (even without definition that this is javascript, the second – you used ‘table’ instead a normal pointer for the sub-elements of your text (paragraphs), lastly, you forgot to wrap your code into a common parent (div id = content) and define paragraphs.

  15. Hey!

    First of all thanks for writing this up! I used this code on a web app im developing that has a bunch of content on one page and instead of just scrolling down, I thought I would add pagination. Now this works fine in firefox, but when I open my webapp in IE 10 or Safari (latest) there is no pagination. Everything just shows up at once and when I scroll down to the paging controls there arent any page numbers there, which was expected honestly. Any idea what might be going on?

    Thanks again!

  16. This demo does not work with modern versions of jQuery in Internet Explorer but Lemuel’s fix above is working. I wonder why it uses 1.3.2 if the article was actually published in 2011 – they were up to at least 1.5 at that point.

    • Hi Bjorn, Do you really want me to update this script to work with the latest jQuery version (for all the possible browsers)?

  17. Great work!!
    I am using particular code for contents inside jquery ui tab..It works well in chrome and other browsers. But, For IE the $(this).html()
    returns blank on click of next page. Initially for first page it loads but the problems comes on navigation to other page

  18. Thanks for the tutorial, saved my life!

    I used Boostrap to style the controls, came out pretty nice :)

    http://anthonyarena3.com/news/

  19. Great work. But I’ve some problem, the “number of pages” is working, but it’s still showing all results… any idea.
    Only using div’s with classes.

    • Hi Luis,
      I can recommend you to check if your page contains any JS errors. You can use ‘Firebug’ plugin to locate these errors

  20. Could you provide us pagination bar rich:datatable using same thing.

    1 2 3 4 5 > Next
    Previous Next ( prevoius show when more then 5 pages)

  21. Great! But can you tell me how can i able to change paginagtions background color?? I mean like this: Page: 1 2 3 4

    • Hi,
      In order to decorate pagination buttons, you may use the following style (example):

      #pagingControls li a {
      background-color: #EEEEEE;
      border: 1px solid #DDDDDD;
      border-radius: 3px;
      color: #000000;
      display: block;
      float: left;
      font-size: 18px;
      height: 30px;
      line-height: 30px;
      margin: 5px;
      padding: 2px;
      text-align: center;
      text-decoration: none;
      width: 30px;
      }

  22. This seems to show blank pages when using the pager links. When populating the content div from Jquery. This is only an issue in IE. Any ideas on how to adjust

    • Hi James,
      I am not sure what we can adjust in case of IE. It might be related on version of this browser. Because it works good in the last version of Internet Explorer (v11)

    • Hi migero,
      Yes, if you change the text content, you need to refresh all internal variables (for pagionation) too. Try to re-initialize the Imtech.Pager

  23. in pager.js

    renderControls = function(container, currentPage, numPages) {
    var pagingControls = ‘Page: ‘;
    minPages = currentPage – 5;
    if(minPages &lt; 1)
    minPages = 1;

    if((currentPage+5) &lt;= numPages)
    maxPages = (currentPage+5);
    else
    maxPages = numPages;

    pagingControls += &#039;’+numPages+’ ‘;
    pagingControls += ‘<a href="#" rel="nofollow">First</a>’;
    for (var i = minPages; i &lt; maxPages; i++)
    {
    if (i != currentPage) {
    pagingControls += &#039;<a href="#" rel="nofollow">’ + i + ‘</a>’;
    } else {
    pagingControls += ” + i + ”;
    }
    }
    pagingControls += ‘<a href="#" rel="nofollow">Last</a>’;

    pagingControls += ”;

    $(container).html(pagingControls);
    }

Leave a Reply to admin Cancel reply