Creating Modern jQuery Pagination for Content

Image Tutorials

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

[sociallocker]

download in package

[/sociallocker]


Lets start coding !


Step 1. HTML

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

index.html

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

css/main.css

01 body{background:#eee;margin:0;padding:0}
02 .example{background:#FFF;width:800px;border:1px #000 solid;margin:20px auto;padding:15px;-moz-border-radius: 3px;-webkit-border-radius: 3px}
03 #content {
04     position:relative;
05     height:400px;
06 }
07 #content .page {
08     position:absolute;
09     top:0px;
10 }
11 .pagination{
12     padding2px;
13 }
14 .pagination ul{
15     margin0;
16     padding0;
17     text-alignleft;
18     font-size16px;
19 }
20 .pagination li{
21     list-style-typenone;
22     displayinline;
23     padding-bottom1px;
24 }
25 .pagination a, .pagination a:visited{
26     padding0 5px;
27     border1px solid #9aafe5;
28     text-decorationnone;
29     color#2e6ab1;
30 }
31 .pagination a:hover, .pagination a:active{
32     border1px solid #2b66a5;
33     color#000;
34     background-color#FFFF80;
35 }
36 .pagination a.prevnext{
37     font-weightbold;
38 }
39 .page_number {
40     border1px solid #9aafe5;
41     color#2e6ab1;
42     padding:5px;
43     text-aligncenter;
44     width20px;
45 }

Step 3. JS

Here are all JS files:

js/main.js

01 (function($){
02     $.fn.extend({
03         MyPagination: function(options) {
04             var defaults = {
05                 height: 400,
06                 fadeSpeed: 400
07             };
08             var options = $.extend(defaults, options);
09             //Creating a reference to the object
10             var objContent = $(this);
11             // other inner variables
12             var fullPages = new Array();
13             var subPages = new Array();
14             var height = 0;
15             var lastPage = 1;
16             var paginatePages;
17             // initialization function
18             init = function() {
19                 objContent.children().each(function(i){
20                     if (height + this.clientHeight > options.height) {
21                         fullPages.push(subPages);
22                         subPages = new Array();
23                         height = 0;
24                     }
25                     height += this.clientHeight;
26                     subPages.push(this);
27                 });
28                 if (height > 0) {
29                     fullPages.push(subPages);
30                 }
31                 // wrapping each full page
32                 $(fullPages).wrap("<div class='page'></div>");
33                 // hiding all wrapped pages
34                 objContent.children().hide();
35                 // making collection of pages for pagination
36                 paginatePages = objContent.children();
37                 // show first page
38                 showPage(lastPage);
39                 // draw controls
40                 showPagination($(paginatePages).length);
41             };
42             // update counter function
43             updateCounter = function(i) {
44                 $('#page_number').html(i);
45             };
46             // show page function
47             showPage = function(page) {
48                 i = page - 1;
49                 if (paginatePages[i]) {
50                     // hiding old page, display new one
51                     $(paginatePages[lastPage]).fadeOut(options.fadeSpeed);
52                     lastPage = i;
53                     $(paginatePages[lastPage]).fadeIn(options.fadeSpeed);
54                     // and updating counter
55                     updateCounter(page);
56                 }
57             };
58             // show pagination function (draw switching numbers)
59             showPagination = function(numPages) {
60                 var pagins = '';
61                 for (var i = 1; i <= numPages; i++) {
62                     pagins += '<li><a href="#" onclick="showPage(' + i + '); return false;">' + i + '</a></li>';
63                 }
64                 $('.pagination li:first-child').after(pagins);
65             };
66             // perform initialization
67             init();
68             // and binding 2 events - on clicking to Prev
69             $('.pagination #prev').click(function() {
70                 showPage(lastPage);
71             });
72             // and Next
73             $('.pagination #next').click(function() {
74                 showPage(lastPage+2);
75             });
76         }
77     });
78 })(jQuery);
79 // custom initialization
80 jQuery(window).load(function() {
81     $('#content').MyPagination({height: 400, fadeSpeed: 400});
82 });

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.

js/jquery.min.js

This is default jQuery library. Available in our package.


Live Demo

Conclusion

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!

Rate article