I was searching for some jquery plugins to do pagination without knowing anything about the content and which can also handle a lot of pages. My friend suggested a excellent one here. I liked the way it worked but had a hard time understanding the algorithm involved. Thus I decided to make a similar one myself to understand the underlying logic. Please note the code I present below is a two hour hack and contains a lot of stupid things that is not recommended.

Update: The code has been completely updated. The code can be found in it's github repo.

View jQuery Pagination Demo

I decided upon the following before starting out with the code:

  • Nothing should be displayed if there is JavaScript is switched off. I suggest you combine this with your server side implementation, if there is any.
  • This plugin will know nothing about the content that is paginated. It will take the total number of pages and some other settings and will just execute a callback function with current page as a parameter. A better way would be to publish the current page over a channel using pub/sub.
  • The markup to use for page number will be a ordered list, since that is the most semantic choice.

The options for this plugin are as follows:

The total number of pages
The maximum number of page numbers to show before and after the currently selected page number
Number of page numbers to show at the start and end
Callback function to call when page changes
Text for previous link
Text for next link

When a page number is clicked the following takes place:

  1. A function is called to highlight the page number clicked and return the current page number.
  2. The next function call adjusts the display of the page number based on the current page number.
    1. If the current page number has less than or equal to adj numbers before it, then it is close to the start. Thus show adj page numbers after it and the last edgeCount numbers.
    2. If current page number is greater than the difference between count and edgeCount then it is close to the end. Show the first edgeCount page numbers and the adj numbers before the current page number.
    3. Else the current page is somewhere in the middle. Show the edgeCount page numbers at the start and the end. Then show the adj numbers before and after the current page number.
If the number of pages is less than (2*adj + 1) + (2*edgeCount) then there is no need do dynamic pagination. Just a list of page numbers are displayed.

Check out the demo here