Creating Modern jQuery Pagination for Content

Creating Modern jQuery Pagination for Content

105 473475
Creating Modern jQuery Pagination for Content

jQuery pagination tutorial. After a short break, I decided to create a new own JQuery plugin for pagination (for different content), which will be based not on the number of elements (childrens) per page, but will take care of the height of the content. And it will try to keep the same height for the pages. This means that the number of elements on the page can be different. Everything will depend on the height of these children. Plus, I will using fade effect to switch between pages.

In beginning – download our package and check demo:

Live Demo


download in package


Lets start coding !

Step 1. HTML

As usual, we start with the HTML. This is source code of our sample:


<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src="js/jquery.min.js"></script>
<script src="js/main.js"></script>
<div class="example">
    <h2>Arkady and Boris Strugatsky. Poor cruel folk</h2>
    <div id="content" class="content">
        <div>The King sat naked. Like a foolish pauper on the street, he sat leaning
        against  a  cold  wall, drawing in his blue, goose-bumped legs. He shivered,
        with his eyes closed, he listened, but everything was quiet.</div>
        <div>He awoke at midnight from a nightmare and immediatelly understood  that
        he  was  finished.  Some  one  weezed and writhed by the door of the bedroom
        suite, he heard footsteps, metalic jingling and  drunken  mummbling  of  His
        Highness,  Uncle  Buht: "Let me through... Let me.. Break it down, hell with
        it..." Wet with icy sweat, he slintly rolled off  his  bed,  ducked  into  a
        secter  closet,  and  loosing  himself  he ran down the underground passage.
        Something sqelched under his bare feet, the startled rats dashed  away,  but
        he  did  not notice anything, just now, sitting next to a wall he remembered
        everything; the darkness, the slippery walls, and the pain from  a  blow  on
        the  head against the shakled door to the temple, and his own unberable high
        <div>They shall not enter here, he thought. No one shall enter here. Only if
        the King  order's  so.  But  the  King  shall  not  order...  He   snickered
        hysterically. Oh no, the King will not order! He carefully un screwed up his
        eyes  and  saw  his  blue, hairless legs with scraped knees. Still alive, he
        thought. I will live, because they shall not enter here.</div>
        <div>Everything in the temple  was  blueish  from  the  cold  light  of  the
        lanterns -- long glowing tubes that were stretched under the ceiling. In the
        center,  God stood on an eminence, big, heavy, with sparkling dead eyes. The
        King continuously and stupidly stared, until God was suddenly screened by  a
        shabby  lay  brother,  still  a  greenhorn. Scraching, with an open mouth he
        gazed at the naked King. The King squinted once again. Scum, he  thought,  a
        lousy  vermine,  catch the mongrel and to the dogs, for them to ravage... He
        reasoned that he did not remember the lout well, but he was  long  gone.  So
        scrawny,   snotty...   That's  all  right,  we'll  remember.  We'll  remeber
        everything, Your Highness, Uncle Buht. During the father's  reighn,  I  dare
        say you sat quietly, drank a bit and kept silent, were afraid to be noticed,
        you knew that King Prostyaga did not forget you ignoble treachery...</div>
        <div>Great  was  the father, the King thought with an accustomed envy. You'd
        be great, if your advisors are God's angels in flesh.  All  know,  all  have
        seen  them:  their  faces  fearful, white, like milk, and their garment were
        such that one could not understand if they were  naked  or  not.  And  their
        arrows  were  fiery,  like  lightning,  they  drove  off the nomads with the
        arrows, and although they casted them overhead, half the horde cripled  from
        fear.  His  Highness,  Uncle  Buht,  wispered  once  upon  a time, drunk and
        burping, that those arrows can be cast by anyone, that  special  slings  are
        needed that the angels have and that would be nice to take from them. And he
        said  then -- he was drunk then, -- that if it is nice to have, why not have
        it, why not... Soon after that table talk one angel fell off the  wall  into
        the  moat,  probably  slipped.  Next  to  him they found one of uncle's body
        guards with a javelin between his shoulder  blades.  It  was  a  dark,  dark
        deed...  It  good  that  the people did not care about the angels, they were
        scary to look at, but it is not clear why is it scary -- angels were  happy,
        cordial  people.  Only  their  eyes  were scary. Small, shiny, and they keep
        racing around... non humanoid eyes, not peaceful. So the people hushed down,
        although father, King Prostyaga gave them such freedom that it  is  shameful
        to  remember...  although,  before  the  Coup, father, they say was a saddle
        maker. For saying so, with my own hands I had torn eyes out, and sewen  ears
        shut.  But  I remember, he used to sit in the evenings by the Crystal Tower,
        and he would cut out leather -- beautiful work. And I would perch myself  at
        his  side, it's warm and comfy... The angels were singing from the rooms, so
        quietly, and in harmony, and father would start  to  accompany  --  he  knew
        their  language  --  it  used to be spacious, nobody around... not like now,
        guards are stuck at every corner, but there is no sense in it...</div>
        <div>The King lamented. Yes, he was a good father, just that he did not  die
        for  a long time. You can't do that while your son is still alive... The son
        is also the King, the son also want's to... But Prostyaga did not  age,  I'm
        over  fifty,and  he  still looks younger than me... It looks like the angels
        had asked God for his health... They asked for his health, but  they  forgot
        about  me.  They  say  that  the  second one they managed to pin down in the
        father's room, he had a sling in each hand, but he  did  not  fight.  Before
        death,  they  say,  he  threw both of them out the window, they burst into a
        blue flame, there was no dust  left...  Too  bad  about  the  slings...  And
        Prostyaga, they say, cried and got drunk then, within an inch of his life --
        the  first  time  since  his  reign  --  looked for me, they said, loved me,
        <div>The King drew his knees to his chin, and hugged his leggs. So  what  if
        he  believed?  One  should  know  one's  limit,  abdicate,  like  it is done
        elsewhere... and I do not know anything, and do not want to. There was  only
        a conversation with my uncle, His Highnesss.</div>
        <div>"Prostyaga, -- he said, -- doesn't age". -- "Yes, -- I tell him, -- but
        what can  we  do,  the  angels  pleaded for his health." Uncle then sneered,
        scum, and wispered: "Angels, -- he said,  --  no  longer  sing  their  songs
        here".  And  I blurted out: "It is true, but now there is a way to deal with
        them, not just with humans". Uncle looked at me  soberly,  and  immediatelly
        left...  And I didn't really say anything... Empty words, without meaning...
        And in a week Prostyaga died from a heart attack. So what? It was his  time.
        He looked young, but in reality he was over one hundred. We'll all die...</div>
        <div>The King was startled, and covering himself, awkwardly sat up. Into the
        temple  came  the  High  Priest  Agar.  Lay brothers were leading him by the
        hands. He didn't look at the King, came up to God and kneeled  in  front  of
        the  eminence,  tall,  hunch-backed, with waist length dirty-white hair. The
        King gloated "It's the end of you, Your Highness, you did  manage,  I'm  not
        like  Prostyaga,  you'll  ravage your oun intestines, drunken swine..." Agar
        spoke in a rich voice:</div>
        <div>- God! The King wishes to speak to you! Forgive him and listen!</div>
        <div>The room fell silent, no-one dared to breathe. The  King  contemplated:
        when  the  great flood happened, and the earth burst, Prostyaga asked God to
        help, and God came down from the sky as a ball of flame on the same day, and
        that night the earth closed up, and the flood  disappeared.  It  means  that
        this  is  how  it will happen today. You were late uncle, Your Highness, you
        didn't manage. No one can help you now...</div>
        <div>Agar straighned up. The lay brothers that supported him,  jumped  away,
        turned with their backs to God, and covered their heads with their arms. The
        Kind  saw,  how  Agar stretced his clasped hands and put them on Gods chest.
        God's eyes lit up. The King snapped his jaw from fear: the eyes were big and
        different -- one was snakish-green, the other white, as bright as light. One
        could hear how  God  started  to  breathe,  heavily,  with  crackling,  like
        consumption. Agar backed away.</div>
        <div>- Speak, - he whispered. It looked like he was unsettled as well.</div>
        <div>The King lowered to all fours, and started to crawl to the eminence. He
        did not  know what to do or how. And he did not know how he should start and
        whether he should tell the complete truth. God  breathed  heavily,  weezing,
        suddenly he started to whimper, quietly and thinly - scary.</div>
        <div>- I'm  the son of Prostyaga -- said the King in despair, smothering his
        face against the cold stone. -- Prostyaga died. I ask  protection  from  the
        conspirators.  Prostyaga made mistakes. He did not know what he was doing. I
        have fixed everything: calmed the people, became great and unatainable, like
        you, I gathered an army... And the treacherous Buht is disrupting  my  plans
        to conquer the world... He wants to kill me! Help me!</div>
        <div>He raised his head. God, without blinking, was looking in his face with
        green and white. God was silent.</div>
        <div>- Help me... - repeated the King. -- Help! Help! - He suddenly thought,
        that he  is  doing something wrong, and that God is indifferent towards him,
        and inopportunely remembered: they said, his father, Prostyaga, did not  die
        from  a  heart  attack,  but was killed here, in the temple when the killers
        came in, with out asking permission. -- Help!.-- he  screemed  desperatelly.
        -- I'm afraid to die today! Help! Help!</div>
        <div>He  hunched  up  on the stone tiles, biting his hands from an unbarable
        terror. Differently-eyed God hoarsly breathed above his head.</div>
        <div>- Old vermine, - said Tolya. Ernst was quiet. On  the  screen,  through
        the  sparks  of  static an ugly black shape of a human lay splattered on the
        floor. -- When I think, Tolya spoke again, -- that if not for him, Alan  and
        Derek would be alive, I want to do something, that you never wanted to do.</div>
        <div>Ernst shrugged his shoulders and moved to the table.</div>
        <div>- And  I  always think, - Tolya continued, - why didn't Derek shoot? He
        could have killed all...</div>
        <div>- He couldn't , - said Ernst.</div>
        <div>- Why couldn't he?</div>
        <div>- Have you ever tried shooting at a human being?</div>
        <div>Tolya made a wry face, but didn't say anything.</div>
        <div>- Well that's what it was, - said Ernst. -- Try to imagine  it.  It  is
        almost as disgusting.</div>
        <div>A  sorowful howl was heard from the loudspeaker. "HELP HELP I AM AFRAID
        HELP..," the auto-translater was writing.</div>
        <div>- Poor cruel folk... - said Tolya.</div>
    <hr />
    <div class="pagination">
            <li><a href="#" id="prev" class="prevnext">« Previous</a></li>
            <li><a href="#" id="next" class="prevnext">Next »</a></li>
        <br />
        <div id="page_number" class="page_number">1</div>

This is sample of content (from one book) plus (in bottom) – some preparaion for futire navigation with pagination.

Step 2. CSS

Here are used CSS file with styles of our demo:


.example{background:#FFF;width:800px;border:1px #000 solid;margin:20px auto;padding:15px;-moz-border-radius: 3px;-webkit-border-radius: 3px}
#content {
#content .page {
    padding: 2px;
.pagination ul{
    margin: 0;
    padding: 0;
    text-align: left;
    font-size: 16px;
.pagination li{
    list-style-type: none;
    display: inline;
    padding-bottom: 1px;
.pagination a, .pagination a:visited{
    padding: 0 5px;
    border: 1px solid #9aafe5;
    text-decoration: none;
    color: #2e6ab1;
.pagination a:hover, .pagination a:active{
    border: 1px solid #2b66a5;
    color: #000;
    background-color: #FFFF80;
.pagination a.prevnext{
    font-weight: bold;
.page_number {
    border: 1px solid #9aafe5;
    color: #2e6ab1;
    text-align: center;
    width: 20px;

Step 3. JS

Here are all JS files:


        MyPagination: function(options) {
            var defaults = {
                height: 400,
                fadeSpeed: 400
            var options = $.extend(defaults, options);
            //Creating a reference to the object
            var objContent = $(this);
            // other inner variables
            var fullPages = new Array();
            var subPages = new Array();
            var height = 0;
            var lastPage = 1;
            var paginatePages;
            // initialization function
            init = function() {
                    if (height + this.clientHeight > options.height) {
                        subPages = new Array();
                        height = 0;
                    height += this.clientHeight;
                if (height > 0) {
                // wrapping each full page
                $(fullPages).wrap("<div class='page'></div>");
                // hiding all wrapped pages
                // making collection of pages for pagination
                paginatePages = objContent.children();
                // show first page
                // draw controls
            // update counter function
            updateCounter = function(i) {
            // show page function
            showPage = function(page) {
                i = page - 1;
                if (paginatePages[i]) {
                    // hiding old page, display new one
                    lastPage = i;
                    // and updating counter
            // show pagination function (draw switching numbers)
            showPagination = function(numPages) {
                var pagins = '';
                for (var i = 1; i <= numPages; i++) {
                    pagins += '<li><a href="#" onclick="showPage(' + i + '); return false;">' + i + '</a></li>';
                $('.pagination li:first-child').after(pagins);
            // perform initialization
            // and binding 2 events - on clicking to Prev
            $('.pagination #prev').click(function() {
            // and Next
            $('.pagination #next').click(function() {
// custom initialization
jQuery(window).load(function() {
    $('#content').MyPagination({height: 400, fadeSpeed: 400});

Here are interesting code, here are and demonstration how to build new extensions for jQuery and also useful code for making pagination. I tried to keep comments quite anywhere to better understanding. This plugin will be able to take 2 parameters (for current moment): first – is the desired max height for generated pages and second – speed of fading effect between pages.


This is default jQuery library. Available in our package.

Live Demo


Today`s article told you about creating nice pagination for content, and also told about creating new own jQuery plugins. Sure that this was useful for you. Good luck!



    • 2 mb
      I prefer Divs instead P, just because this is block-based elements with own height, It allow keep text parts in separated parts (paragraphs).

  1. Good sir. Instead of Fade effect…of each page I want to make as slide. Fr that what i do. I used slide….instead of Fade it is not functioning…

    • You can use slideUp / slideDown in showPage function, plus, I can suggest you to change or z-index or visibility too

  2. Well. When i split it into 2/3 columns using CSS for each div, there is an space at end of the last para of each div. (it is the total space of no. of paras flown as single column in a div). I think this can be solved if the content is split by lines as the div height instead of pharas. Any solution please….

  3. Sorry for the confusion. In your above demo, first page can accomodate 2more lines in bottom (upto the full div height). The same way the 2 page can accomodate 4 more lines. But the split is depending on Paragraphs hence the space is left on the each paginate div. If the content is split by no. of lines (not paragraphs) according to the div height the white space can be reduced in each paginated div. Is it possible.??.

    • Hi sv kumar again :)
      firstly .. this can looks in IE and FF a little differently. In FF it haven`t any space at first page. But second page – yes, have a little of free space.
      commonly – how it working:
      * we walking through all childs of our parent element
      * we starting to add height of child to some variable (height), and placing this element to array of elements of first page
      * in case when adding next element height to our variable (height) will exceed limits, we switching accepting page, nulling our variable to 0, and continue walking again

      so in result we have some set of child elements separated by pages.

      we can`t work with lines of text inside our childs. Just because even children can be difficult element (can have own childs with different content).
      This is because I selected this way of working.

      One of alternative solution (not sure that will fine for not text based content) will calculation total height of all childs, and separate it by pages not by elements itself, but using some height of each step (paginate). Where we will shift inner content via margin/paddings each time when we need to choose another page.

  4. sorry to disturb u again. Break the Paragraph to the height of the div will avoid the empty space in the div’s. Egarly waiting for ur help.

  5. Any idea how can i just load the new content of the new page in the click instead of everything is already loaded? It´s no good for perfomance.


    • 2 CE
      As usually – text content have weight much less than styles, scripts, images. So this is ok to load many pages (paginated) at once. But in case if amount of text can be >200kb (as example), yes – will need to think how to load content dynamically. You can prepare some element like ‘Next’ which will load ajaxy new portion of content, this content we will need to append to our <div id="content"
      And, we will need to add our new ‘page’ to inner variable: paginatePages
      This variable contain array of pages which we can switch

  6. in your above code, the first page can accommodate 2lines in the bottom of a div, as also 2nd page can accomodate 3 more lines. But the split is between paragraphs and the space in the bottom of each div looks ugly. Is it possible to split the paragraphs and distribute lines in both divs…

  7. Hello!
    Tell me, please, how to do pagination for DIV elements, for display on the page just 3 divs example… or 4 or 5.. Sorry for my english.

    • 2 flenj
      This is already done, I don`t using here any defined amount of childs (divs) per page, it always depends only on height of childs. So can contain different elements per page.
      If you should have exact amount of childs per page – check my old post – where I used another pagination

  8. Hi,
    First of all I would like to thank you for the script. It’s really simple, lightweight and slick. I wondered, since your solution which highlights active element via :active pseudo-class works only in IE (in FF it works with :focus while in webkit browsers it does not work at all), is there a chance you could add a selection of the active element from within JavaScript? I guess it could be done by creating a CSS class through a function, though I’m quite new to JS, and therefore not able to do it by myself. I’m sure everyone will find it useful.
    Thanks in advance,

    • 2 Eli
      Are you talking about CSS selection: .pagination a:hover, .pagination a:active ?
      If so – are you sure that it working only in your IE7
      Just because it working well in all my browsers (FF4, IE7-9, Chrome) – it successfully highlighting element on mouse hover in pagination

  9. It surely works in all of them on mouse hovering. What I meant was the highlighting of the current page, e.g. if right now you are reading text on page 3, the number 3 should be highlighted. Currently in Chrome there is no way to know, on which page you are.

    • Yes, this is possible too, I made few changes, firstly – css:
      .pagination a {
      border: 1px solid #2b66a5;
      color: #000;
      background-color: #FFFF80;
      after – JS:
      search for
      and add next 2 lines below:
      $(‘.pagination ul li’).removeClass(‘active’);
      $($(‘.pagination ul li’)[page]).addClass(‘active’);
      these changes will assign ‘active’ class for active (selected) pages.

  10. hi, love the script.

    but im trying to use this script on 2 divs on 1 page, but it isnt working at all.
    can you maybe eddit the code to make it work on 2 divs?

    Thanks very much!

    • Hello Dave,
      Maybe you should just increase height of page?
      Pay attention to
      height: 400
      in our script. Here are no difference what you using inside, it can be and divs and another elements.

  11. Thansk for your code!
    BTW how can i create autopagination – depend on screen height? height: ‘auto’ & height:’100%’ doesn’t works (((

    • Hello elvencedor,
      You can apply autopagination for defined hight in %, Just keep in mind that we still need to have a little space for pagination itself (in bottom of page). So, let remove all unnecessary elements from page, and, assume that we need to our content 90%, and another 10% for pagination. So, lets change initialization from
      $(‘#content’).MyPagination({height: 400, fadeSpeed: 400});
      var iHeight = (window.innerHeight * 0.9);
      $(‘#content’).MyPagination({height: iHeight, fadeSpeed: 400});
      this is example of course, but in this case we will pass to our plugin correct client height. And pagination will work :-)

    • Hi demdemdem,
      Do you want to customize these Prev/Next links or what?
      In my last answer to Eli I mentioned changes to highlight active page, do you need same?

  12. Not to highlight the active page, but to set a class to the Prev/Next links when either the first or the last of the paginated div is currently displayed.

    In that way, when the first paginated div shows, the link Prev would be disabled (as logic dictates), and vice versa.

    Any clue how we can make this happen?

    Many thanks for your great work.

    • I have reviewed this code again, and can suggest to change

      (in initialization)


      if ($(paginatePages).length > 1) {
      } else {

      Thanks for your notes.

  13. hi :) thanks for sharing this very interesting code. i’m very new on JS coding and can’t find one little thing, perhaps you cloud help me on.

    How could i have it working on instead of ?

    Thanks by advance for your help :)

  14. oups the question is to have the script working on P instead of DIV i do not know why i do not appear on my last comment :s

    sorry for that, my bad.

    • Hello Cali,
      Yes, we can make script work with P tags instead DIVs, You have just change all DIV’s to P’s tags in our content element.
      All because rest JS works with all childs of our parent (div with class ‘content’). And, it there are P elements (and not DIVs), it will work with them without problems.

  15. Hello!

    First of all, Thanx and congrats for the plugin!
    I need help to set the pagination to display the page top everytime the page changes.
    Don´t know why, but it automatically goes to page bottom when changing pages or either refreshing the page.
    Please help me solve this.

    Thanx again! B. Regards!


    • Hi Chibru,
      As I know – script doesn’t should scroll at all, it should refresh content (ajaxy) only. Recheck – it doesn’t should scroll.

  16. I have 2 DIV’s:

    ————div 1————-|
    height: 450px
    ————div 1————-|

    ————div 2————-|
    height: 300px
    ————div 2————-|

    and when in script: “height: 500px” and in css: #content “height:500px” script generate only one page – display this two dives.
    Is this possible to “tell the script” move incomplete div to the next subpage – in this example make 2 pages (on first display “div 1” and on the second display “div 2”).

    Of course this is very simple example :)

    Thanks for any help.

    • Hello oskar,
      Are you sure that your 2 divs have heights 450 and 300?
      I’ve just prepared the same example with text, and, my script separated this 2 divs into 2 pages (as expected).
      If you like – I can publish this example somewhere. Do you have this problem at remote host or at localhost?

    • Hi Hazem,
      As I know, jQuery is a js library, which has nothing to do with JSPs, except on specific requirements like Ajax calls.

  17. This is a very nice tut and have been very usefull but i have one question how can i refresh the paginator because my content div gets updated sometimes and then i have to reload the paginator and now it just keeps adding paginator fields.

    • Hello Jack,
      In case if your content gets updated periodically – you have to re-initialize everything, try to call initialization function ‘MyPagination’ again

  18. Hello,

    first of all, thanks for the code. I want paging script that works in mobile (using phonegap), and your code work perfectly.. :)
    but, i have a little problem.
    Imagine that i have two paragraph (i separate into two divs)
    how can i display each divs in one page, so imagine if i have two divs, it will separate as two page too..
    the page’s height also increase and decrease dynamically based on the div’s height…
    any solution for this problem?
    thanks before.. :)

    • Hello febrizio,
      If you need to display every div at separated page, you can:
      * or – modify our script to display every div as a separated page
      * or – you can measure your div’s heights, and – initialize pagination with similar (a bit bigger than you measured) height.

  19. hi – i need to have 2 contents to display in 1 page, each will have different pagination, pls help me how to do it.


    • Hello Mike,
      In the current realization it is not ready to work with multiple instances. Because besides of adding unique IDs, we will need to use multilevel arrays to keep info about pages. Most of JS code should be rewrite in this case.

  20. Hi,

    For the same content, the splitting of pages is different for IE and Chrome, this is because the clientHeight value is not calucated in IE. I want the same number of pages to be displayed in across browsers, how to fix this issue?

    • Hi Aps,
      Yes, height can be different in IE browser, .. you can read about it here:

    • Hi owais,
      What do you mean – ‘subpages’ ?
      Do you want to make pagination with multiple sublevels?

  21. Hi,
    You saved me a ton with this example. it works great.
    but in my instance
    I have 2 DIV’s:

    ————div 1————-|
    height: 650px
    ————div 1————-|

    ————div 2————-|
    height: 300px
    ————div 2————-|

    and when in script: “height: 500px” and in css: #content “height:500px”
    the first div is practically more than the height specified. when i try this script the text just overflows and doesnt seem to break into the next page.
    any help on this much appreciated
    thank you

    • Hi sainisha,
      I can suggest that you enlarge both params (both heights): and in JS and in CSS file, or, you can also try to decrease height of your first element

  22. Great tutorial, how would you go about only showing the next and previous buttons if required, for example if there was only 1 page you would not need the next/previous buttons. Would you use php or JQuery or something else? Thanks

    • Hello Dave,
      Yes, sure, you can use our script, but you will need to modify it (in order to hide number-based pagination)
      As example, you can hide ‘showPagination’ on line 55, and, any time you evoke ‘showPage’, you will need to calculate if you need to display Next or Prev button (and – hide it if you don’t need)

Leave a Reply to Andrey Cancel reply