PHP Page List Generator

Update: April 3rd, 2008

View the example & the source

At the bottom of most web pages you have the ability to navigate through other pages of the content. This is used everyday by people at Google, Yahoo!, and Digg (see the very bottom of their webpages). This function was modeled after the page browser used on Digg.com. Some ideas that are implemented:

  • Always shows the begining and last few pages. The idea is that people will typically always want to go to either the begining or the end
  • If the current page isn't near the beginning or the end, show the page number in the middle, and show page numbers around that number.

Some examples:

Page near the beginning of the list:

pagenav_begining.png

Page at the end of the list:

pagenav_end.png

Page not near the beginning or end of the list:

pagenav_middle.png

So thats what the function generates, with a little bit of CSS added. The function takes 2 parameters, which are function($currentPage, $totalPages), with the $currentPage as the current page on (go figure!), and $totalPages as the total number of pages (again, go figure). So to make the lists shown above, the following function calls would be made:

  • generatePageNav(2, 59);
  • generatePageNav(59, 59);
  • generatePageNav(48, 59);

Live example

You can see a live example at the pageNav example page. To see it work, try clicking on page 100 (notice the ?page/{pagenum} in the URL), and then try clicking on page 7. After doing this you will see the list transform into what is in my opinion is the most logical presentation. This example also shows some basic CSS, which leads me to the next major point the CSS structuring.

CSS explination

So the generatePageNav function returns something that looks like:

<ul id="pages">
  <li>
    <a href="/page/1">Prev</a>
  </li>
  <li>
    <a href="/page/1">1</a>
  </li>
  <li class="current">
    2
  </li>
  <li class="noclick">
    Next
  <li>
</ul>

In this case, there are only 2 pages, and the user is currently on the second page. Notice that the "next" button is not a link because the user is on the last page. Here's some explanation of the CSS:

  • ul#pages - the main ul container
  • ul#pages li - the li container that holds the link
  • ul#pages li.current - the current li that has the link to the current page
  • ul#pages li.noclick - the disabled "next" or "prev" buttons (this is not a <a href when on the first or last page)
  • ul#pages li.dots - the li that contains the 3 "..." between the first or last boxes

The code

Finally, the part you've been waiting for: the code. You may view/download it and use it in whatever projects you would like. If you do use it, have any problems, or have any improvements, let me know in the comments.

No comments yet.
TOP