Creating Modern jQuery Pagination for Content

Creating Modern jQuery Pagination for Content

105 94685
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

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!


jQuery Mobile Lesson 2

0 525
jQuery Mobile Lesson 2

0 585


  1. Hi! I have a problem with the code. My text go out of these 400px. And I see only number 1 – no other numbers and nothing work :( Actually these 400px are not good for mee – i want 2000px because i have many content. But this is the next step. For the moment the JS code doesn’t work for me. The way is correct to the both JS files. Would you help me, please?

    • Hi Plamen,
      Are you sure that you need 2000px for height? What is your monitor for this dimension – 40″? :-)
      Anyway, did you try to play with Height param in JS and CSS files? Try to enlarge these 400px

  2. Hi! Thank you so much for this code! I hope you can help me with this nightmare I am having… :-) I am new to JS, and I am trying to replace the divs with imgs, but I need to display 10 images in 2 rows per page (5 img on each row at large screens) then if the screen resizes at a smaller size, there should still be 2 rows of img but with 4 img per row, 3 if smaller, 2 if less, etc… and the other images should move to the next pages. The problem I have is that it looks like it takes the height of the images, and as 3 of them reaches the height specified (although they display inline) it shows only 3 images per page, then I have blank space. I have space to the right to fit 2 more images, but they are not showing. Hope this is not too confusing for you! Thanks!

    • Hi cecilia, I can recommend that you put all your images inside of DIV elements, you also can add a rule float:left for these images (or – display:inline).

  3. Hello. I tried using your script. but my needs are a bit different. I have a bunch of fixed width and height (square, 133x133px with 5 px left and bottom margins) items and i would need to split these in pages, with as many rows and columns as I can fit in the containing div. The containing div’s width is way larger than the items’, but your script calculates according to the height given. Is there a way to get it to count how many items fit in a row and in a column and split them according to their multiplied values?

    Hope that makes at least some sense :))

    • Hi Reddo,
      Basically, your demand is very similar as cecilia’s, but she mentioned images. Anyway, try to align your images from the left to the right, and keep all your objects inside DIVs

  4. Hi! This script is excellent and works well. I want to ask something though: Can it be made to work if the #content .page is not set to absolute positioning, but in relative instead? You see, i have a float image, and i want the paginated content around it. This happens only if i change absolute positioning to relative, but then when a page is changed, a strange issue appears where the text moves below and immediately afterwards into place. I would like the transision/fade to happen as it happens with absolute positioning.

    Secondly, this would be more of an improvement, the next and prev links do not load the next/prev page in an ajax way like the numbers in the pagination do, so you end up seeing the top on the page.

    Sorry if my english were not good enough to make you understand my issue and for any trouble i am putting you through :)

    • Hello Kostas,
      Yes, sure, it is not a requirement to have this absolute positioning for .page element, if you like, you can use the ‘relative’ positioning. But in this case you will need to modify the JS code to make better smooth transitioning between pages.
      As for Prev/Next elements, they work, I have just checked it. But, it you noted that it adds ‘#’ to the address bar, it is easy to overcome it, just add ‘ return false; ‘ for both onclick handlers.

  5. Hello, Excellent and simple plugin. But, I also want to do following thisgs:
    1) Disable the page link, that has been selected.
    2) Disable ‘Prev’ if I am on first page.
    3) Disable ‘Next’ if I am on last page.
    Can you tell me how can I do that?

    Thanks in advance…

    • Hi Vishmay,
      It is not very difficult to disable Prev/Next links in case of the first or the last page. You will need to add some code to compare a current page (lastPage) with a total amount of pages ( $(paginatePages).length ).
      And, if your current page is 1 (first page) – just disable the ‘Prev’ link, in case if your current page = total amount of pages, disable ‘Next’ link.

  6. Hi, very nice plugin.

    Would it be possible working with a editable content ? so that the paging will be recalculated with each key press

    Thanks in advance…

    • Hi Mike,
      This is possible, but, I am not sure that this is a very good idea to recalculate everything on each key press, this is not optimal.

  7. Hey Andrew!

    Nice post and very useful but i have come up with some issues with this code.
    I have the same task to be done where a dynamic height of DIV and there should be no-limit of the elements or elements are placed.
    I have tried this thing and came to know when i place simple lore ipsum paragraph tags to fill the space it doesn’t create the next page and that content overflows its parent.
    Why is happening to me?

    • Hello Akshaya,
      I don’t know exactly, but I can recommend one thing, in case if you are ensure about every heights of inner elements, it would be prudent to go through all child elements in order to find a max height if a child, and, to define the max height if your parent element (page) depending on the max of the child.

  8. Nice piece of code.

    Adding this css line p {display:block;padding:0;margin:0;} allows to replace divs in the markup with paragraph elements (p) .


  9. Hello. Can this script be modified so if there is only one page it won’t draw switching numbers and prev/next links(the whole pagination area in general)?
    What i mean is, sometimes one can have very long articles that look beautiful once paginated with your script in 4-5 pages, but there are some articles with very small content,and thus you end up having pagination controls for just one page.

  10. Hello, thanks for the code, but I have problem: I use the code in tbody table, it works but broken css, any idea? :(

    • Hi scizor,
      I think that it would be better if you show me your problem. Right now it is difficult to predict what is ‘broken css’ in your case (You can use the contact form in the bottom of website)

  11. Sorry for the above post, I forgot to enclose my code in code tag. So I am posting it here again.


    In Your pagination html, you were using class “pagination” on parent DIV and then child but I am using the below html for pagination:


    And now for applying active class to current page, I use your this code which you suggested in above comments:

    // and updating counter
    $('ul.pagination li').removeClass('active');
    $($('ul.pagination li')[page]).addClass('active');

    But now when I refresh page, I get the active class on NEXT .i.e. on the below list item


    Though it should have been on first page, any suggestions on where to make changes? Kindly do post code to support your answer as I am a newby in Javascript :(


    • Hello Syed,

      You will need to move the following code:
      higher, please put it before the earlier ‘if’ statement

  12. Hi I managed to do the above myself. Can you please help me with one thing, that is I have two divs but float left and float right and it can be accommodated within one page. But using this plugin it make first div (which floats to left) one page and 2nd div (which floats towards right) the 2nd page.

    Can you please help on how to make it display on a single page? And also disable this pagination if the content is only one page.

      • Hi Daniel,
        Yes, everything is possible, but this is not a standard feature of this script. It needs to be developed.

      • Would you like to help me out with such a feature? Or at least give me some pointers on how to achieve this? I would be very grateful!

      • Hi Daniel,
        Yes, I can develop this solution for you (as work, for some beer maybe).
        In general, the logic is: When you list all children of the parent (in the beginning of the ‘init’ function), when we calculate heights, we need to add some code that will check if an element of certain type (maybe by it’s class or id). If it so, you need to enter, push content into new page, reset height and subPages array.

  13. Thank you so much for this script! I’ve been to the end of the internet looking for a script like this because I’m building a website with a small CMS where content is distributed over A4 size pages. Besides printer friendly pages I can now generate a pixel perfect PDF file.

    Kind regards,
    Daniel Wichers (The Netherlands)

    • can you lend me a hand. i need help in displaying large HTML content like A4 sized pages one below another with page breaks and page numbers.

      Appreciate any help in this regard.

      Thanks on anticipation

  14. Thanks for this code. Very useful. But I am not a programmer that is why I have such problem:
    -how to combine 2 codes – one which sort info by attributes and result must be divided into pages using your code.

    first code is (of course, i’ve changed attributes accoring my info)
    $(function() {
    var newSelection = “”;
    $(“#flavor-nav a”).click(function(){
    $(“#all-flavors”).fadeTo(200, 0.10);
    $(“#flavor-nav a”).removeClass(“current”);
    newSelection = $(this).attr(“rel”);
    $(“#all-flavors”).fadeTo(600, 1);

    (I have copied it from here

    All what I can is to divide all info to pages and then filtering info on each page separetely.
    But I need first to filter info and then divide it to pages.

    Please help me. I try to change your code for several days but not successfilly
    Thanks in advance!!!!

    • Hi Viktor,
      Your problem is fairly unusual. I think that you can try to re-initialize the pagination code right after you finished filtering the initial list of entities, something like that.

  15. Hi!Sir~!im not english guy, im in the DUBAI, i come here for help, I’m making a small function… but fortunately i found this web site(tutorial)… i want to add one function more… when i click next button, i want see first page.. what i mean is i want to make this to circulate continuosly… please help me

    • Hi Leona,
      You need to add a checker into the ‘showPage’ function, where you will check if a clicked page is out of possible range (of available pages)

  16. Hello ,

    I want to show fixed number of page.Because instead of showing i will show 3 pages from current page like 3 pages at any point

    Best Regards

  17. Hi,

    I like your code, but I just have one question.
    Instead of the current page number at the bottom of the ”pagination”, is it possible to actually see the current page on de ”pagination” bar it self.


  18. Thank you very much for sharing your wonderful plugin. Just encounter one issue. At times the navigation page numbers are on top of my div content. I tried playing with div heights inside jquery and css files but that didn’t work. I also tried changing position from absolute to relative and vice versa for content n page divs but that didn’t help either. Can you suggest some other solution please.

  19. How can I show all the pages one below another like in MS word document, with page breaks and page numbering.

    Any hint would be appreciated.

    Thanks in anticipation.

    • You may play with CSS to show all (even hidden) pages.
      But, I’d recommend that you prepare the necessary html layout directly on server, it probably will take less time

  20. i have 10 pages of content but my script is working for only upto 5 pages and my page does not show more than 5 pages please help me

  21. Can this code use for specific div class or id instead of div height as below:

    The content of content 1 and content 2 should be on one page irrespective of their height.

  22. Hello Andrey,
    you your solution is great, thanks for developing it.
    I’d like to ask you if you have advanced in displaying two pages on a screen, instead of just one.
    Also, what is the main parameter that makes some text to surpass the page? It happens on occasions that text surpasses the content box, and I’m not sure what causes it
    Thanks again!


    • Hi Sebastian, I haven’t got the ready solution to display 2 pages at once. But the idea can be implemented if you change javascript code with having in mind that you need to get 2 times less pages (for pagination), and then you will display 2 pages at once. Or, you can visually display that one page looks like 2 pages.
      With regards to parameters, the height is one of them, try to make it bigger if you think that some internal content can be bigger.

  23. It was very useful.Thank you for this script! But I have one problem with your code. In the demo itself, the content height() is varying from one page to another. How to get equal height of the content to be load ?. So that it will have similar look.
    Can you please guide me for this problem.

Leave a Reply