Tuesday | 05 NOV 2024
[ previous ]
[ next ]

Page Numbers Navigation

Title:
Date: 2023-06-12
Tags:  html, cheatsheet

I always needs some basic page numbering logic whenever I have results. Instead of re-creating the logic from the beginning, I'm going to write it down here so that I can reimplement it as needed. The idea solution would be for this to be a proper component but alas, I don't use frameworks enough to actually do it.

The core of it is that I want to display a list of 5 pages, the middle should be the current page we are one and it should make sure it looks good on the first page and the last page.

< 1 2 3 4 5 >

This should be how the first 3 pages should appear.

< 3 4 5 6 7 >

Now this is how page 5 should appear. The downside is that we don't see the ending page but we can easily add that with ... and page total. I could also add a double angle bracket that will take us to the first and last page.

For now however this is fine and we can get to the code.

My way of doing this is to build an array of the page numbers that I need. I also want the current page to have an even number of pages on either side.

   let currentPage = 1;
   let totalPages = 100;
   let pageNumbers = [];
   
   let start = currentPage - 5;
   let end = currentPage + 4;
   
   if (start < 0) {
      start = 0;
      end = 10;
   }
   
   if (end > totalPages) {
      end = totalPages;
   }
   
   for (let i=start;i<end;i++) {
      pageNumbers.push(i+1);
   }

The start and end postions are there so that we can get an even number of pages on either side. This will also take care of the case when we need too many pages and when there are too litle pages.

Now in Vue we can simply do:

<ol class="flex">
   <li><</li>
   <li v-for="p in pageNumbers">{{p}}</li>
   <li>></li>
</ol>

This will give us a page numbering like the ones above. We can then add click events and write the functions to go to a specific page, to go to the next page and to go to the previous page.

Hopefully at some point I'll have something better. I could use the start and end directly in the v-for but I like array of numbers as it makes more sense in my head.