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.
I decided upon the following before starting out with the code:
- 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:
- A function is called to highlight the page number clicked and return the current page number.
The next function call adjusts the display of the page number based on the current page number.
If the current page number has less than or equal to
adjnumbers before it, then it is close to the start. Thus show
adjpage numbers after it and the last
If current page number is greater than the difference between
edgeCountthen it is close to the end. Show the first
edgeCountpage numbers and the
adjnumbers before the current page number.
Else the current page is somewhere in the middle. Show the
edgeCountpage numbers at the start and the end. Then show the
adjnumbers before and after the current page number.
- If the current page number has less than or equal to
(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