How to create easy pagination with jQuery

How to create easy pagination with jQuery

113 417085
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. If your content is tall enough to cause a vertical scroll, and you then click a paging link, you do NOT scroll back to the top. Is this preferable to the normal page refresh behavior? Not to me.

  2. Why would you want to use pagination at all for such a small dataset? Pagination is meant to break large sets of data into smaller chunks to reduce network traffic. You cannot send 10’000 objects to the client, right?

    Client side pagination does not make any sense to me. Besides, pagination should change the url. Otherwise, you cannot send the url of “page 3” to a friend.

  3. What I like is the ability to name the paragraphs that should be paginated.
    All the other jquery plugins just take all children of the container, which is not detailed enough for a lot of use cases.
    @Gernot
    Basically I agree with you. But not every design wins if one needs scrolling. Imagine a sidebar which displays concert data, say 3 at a time and the total of entries is around 20. Then, IMHO, it’s perfect to load all data and display small fractions with client side pagination.

  4. I am trying to integrate a dropdown element that dynamically changes the value of paragraphsPerPage on change. Do you have any idea of how I can do that?

    • Firstly, you can obtain this event via $(“your_dropdown_selector”).change(function() { … });
      and inside you can change our pager value:
      pager.paragraphsPerPage = $(this).val();
      as example, next, possible will need to re-initialize pagination via
      pager.showPage(1);
      try this

  5. It’s not much of a tutorial, it’s more “here’s some code that does paging”… and the paging effect isn’t very pleasing – counting paragraphs inevitably leads to uneven page sizes. Defining a vertical page height and then intelligently splitting the content into pages according to that height (rounding up/down depending on the size of the paragraphs) would be much better, but alas that’s not what it does.

    • Yes, truly, at present it isn’t based on height of a generated element so can lead to that that heights can be different. But this will fine in case if you using similar (by size) elements. As example for galleries, list of objects etc. When I`ll find something good to paginate different size objects – I`ll tell about it obligatory :)

  6. Hey, what a strange loop in showPage, use .slice() to get specified part of array, Luke :) Also script destroys source block (inline styles, attributes etc.) Something like this will be much better


    this.blocks.slice( (page-1 ) * this.blocksPerPage, /* start */
    ((page-1)*this.blocksPerPage) + this.blocksPerPage /* end */
    ).each(function() { html += $(this).clone().wrap('').parent().html()}); //get outerHTML (lol)
    $(this.pagingContainer).html(html);

    • 2 JTG
      Yes, thanks for corrections, but I have even better suggestion (which will prevent removing inner styles, attributes)
      1) change our paragraphs from

      to

      as example
      2) don`t forget to point it in initialization: pager.paragraphs = $(‘div.z’, pager.pagingContainer);
      3) and, here changes for ‘showPage’ function, instead our FOR loop, lets use slice, but I changed your code to:
      this.paragraphs.slice((page-1) * this.paragraphsPerPage,
      ((page-1)*this.paragraphsPerPage) + this.paragraphsPerPage).each(function() {
      html += ‘<div>’ + $(this).html() + ‘</div>’;
      });

      no need clone or wrap, all more easy :)
      I`ll change our article with updated code

  7. Tnx for sharing.
    Im going to try this with my application but i dunno how far this code is going to help..!!

  8. can u please guide me to get the code for defining a vertical page height and then intelligently splitting the content into pages according to that height…

    • 2 sajjakumar
      Commonly, you can use: document.body.scrollHeight
      to determinate height of page (even it have scroll)
      but after, it will not so easy to determinate how many elements (childs) will need to keep per each page, just because height of each child element can be different (depends on its content), so you will need to check height of Each child element before making pagination.

      • Update, .. possible today I`ll prepare new post where I made own new pagination method :)
        which will work as you want

  9. Thank for ur reply….
    A single div containing raw text which can be fitted in 100×100 px div and remaining content (which is in hidden) also fit the same 100x100px div displaying with prev/next buttons using height of the div instead of paras…

    • 2 sajjakumar
      Please check my recent (new) tutorial about pagination, seems that this is what you looking for

  10. This is brilliant. I had a one page gallery and this has helped me paginate it. I played around with the position of the page numbers to get them at the top and all works well.

    Apart from Internet Explorer. Using images with this plugin, in IE makes for empty images.

    Good work though!!!

    Thanks
    J

  11. Thanks a lot….It works…
    can i have nay suggession regarding paginate info as 2/5 of 5/5 instead of 1 2 3 4 5

  12. 2 sajjakumar
    Yes, sure, this is easy, make attention to ‘renderControls’ function, it generation set of navigation
    and, just replace
    ‘<li><a href="#" onclick="pager.showPage(‘ + i + ‘); return false;" rel="nofollow">’ + i + ‘</a></li>’
    to
    ‘<li><a href="#" onclick="pager.showPage(‘ + i + ‘); return false;" rel="nofollow">’ + i + ‘/’ + numPages + ‘</a></li>’

    all easy :)

  13. Thanks Sir…. It works well. But it displays as 1/3, 2/3, 3/3. My idea is to show current page only. suppose i click the 2nd page it should display 2/3 only. If i click next it should show as 3/3. Sorry for troubling again

    • If we will display Only current page, how you will able to switch to another pages? :)
      I can suggest you to display current page number somewhere else, near pagination itself

  14. Thanks for ur prompt replay. I used PREV / NEXT for the browsing pages..

    pagins += ‘<a href="#" rel="nofollow">’ + i + ‘/’ + numPages + ‘</a>’;
    }
    $(‘.pagination li:first-child’).after(pagins);
    };

    // perform initialization
    init();

    code not copied correctly. Pl. check now if it is possible pl do the needful sir

    // and binding 2 events – on clicking to Prev
    $(‘.pagination #prev’).click(function() {
    showPage(lastPage);
    });
    // and Next
    $(‘.pagination #next’).click(function() {
    showPage(lastPage+2);
    });

    • Commonly all correct, just use
      pager.showPage(lastPage)
      instead showPage(lastPage)
      and, you will need to define somewhere that lastPage too

  15. Hi there, i’ve been testing this code to create a simple pagination (obviously) and couldnt manage so far to get it work a 100%.

    I got a WordPress site, and on one page i’m generating a list of events (thanks to the Event Calendar Plugin). This is where i’d like the pagination to come to life. I set up all requested elements and it seems to work as i get the correct pagination showing up at the bottom. But my blocs that should be paginated are all displayed.

    If i change the pager.paragraphsPerPage parameter, it does update the pagination numbers at the bottom but still, i get all the blocs.

    My ‘blocs’ are in fact tags within a . I thought that could be the reason why it wasnt working, so i tested this configuration in a minimal test page, one with an id for the pager.pagingContainer parameter and a list of for the pager.paragraphs parameter. And it works fine, with no css at all.

    Any chance someone’s ever seen this bug?

    • Hello Kevin
      I suggest you to re-check values: pagingContainer (this should point to parent of paginated units), and paragraphs (units itself). Possible you mess something?

  16. Hello,

    Amazing script..

    One doubt .. I am using this script to paginate some form items.

    A list of items gets populated from the database. It has some text fields and some check boxes. If I enter some value in a text box or check a checkbox on page 1, when I move to page 2 and come back to page 1 the values get reset.

    Is there a way to retain form values from one page to another.

    thanks

    • Hello Nitish
      Are you tried our new ‘Creating modern jQuery pagination for content’ ?
      anyway – you can write me email through ContactUs form (and tell me your demo/live url), and I`ll try to suggest you something

  17. hello i just want to ask how to create alphabetical (A-Z) pagination instead of Number (1-9), but i want to create a list in such a way so when you click on letter A it should only show A list only not all the list below. if you click B it will show only B list. how will i make like that??

    • Hello Irne,

      Yes, you can of course, pay attention to function ‘renderControls’
      You have to modify it. You need to draw alphabetical letters as value of LI elements. You can do this with using ordinary arrays. Try to think how to make it – this is not so difficult.

  18. Instead of a numbered menu is it possible to have titles? Perhaps use the id of the div as the title? That would be the bomb!

    • Hi webmelbs,

      Yes, generally this is possible to create alternative version of pagination but with text-based pagination (titles). Would you like to see such version?

  19. I have a page that has tabbed content. I want the pagination to only allow 8 images per tabbed content holder. I have the first one working, but I need to get the second tabbed content to work. How do I add multiple instances of this pagination script to the same page?

    If you need to see my code let me know. :)

    • Hello Tabetha,
      For multiple instances we have to improve our script. We have to make better selectors. One of easy solutions – make 1-2 new functions to pass necessary selectors for pagingControlsContainer and pagingControlsContainer variables. Because we have single selectors right now.

    • 2 brijendra kumar
      Yes, you can modify this script can use height of objects instead paragraphsPerPage param. As example, you can check our related article ‘Creating Modern jQuery Pagination for Content’

  20. Great script. I am trying to incorporate this to use with a gallery of images. I am using jquery lightbox evolution for the image part and have the pagination working perfect in both FF and Chrome. However in IE8 & 9 it only shows the first page of images. As soon as another page is selected all images vanish. Any thoughts as to why this only happens in IE and how I may fix it?

    http://www.scottamayer.com/example35/

    Many thanks
    Scott

    • Hi Scott,
      First – fix you demo, because it contain JS errors right now (404 Not Found).
      Your lightbox was not attached.
      And after – don’t forget to re-initialize this gallery after we switching pages.

  21. Thank you for the nice script. It’s working well, but if I like to use jQuery colorbox inside for images I’m still running into trouble and colorbox doesn’t appear. The same, if I set one of both in noConflict().. Any idea how to solve?

    • Hi QM-B,
      Hmm, I think that you will need to re-initialize your colorbox (if this is some jquery plugin) any time when we click to pagination links, what do you think?

  22. It is not working in IE 8/9 with jQuery 1.7.2, but if you downgrade to 1.3.2 (like in DEMO) it is working. Please fix this problem.

    • Hi k0s,

      Yes, possible, due changes between jQuery versions.
      Can you point me to line number which have js error when you use jQuery 1.7.2
      and I’ll prepare you that fix.

  23. Hello friends, I want to use PREV / NEXT for the browsing pages…also regarding paginate info as 1/5 2/5 3/5 …
    I’m not able use the exemple in top because ,I ‘m beginner in JQuery
    please friend help me if you can give me the code complet .
    thank you very much :)

  24. Same problem with IE 8/9. First page display is fine. After that pages are empty because $(this).html() is always empty. In fact, every (pages.paragraphs)[i].innerHTML is set to ”. There are no .js errors, just empty pages.

1 2 3

Leave a Reply