pagination in javascript

Simple Pagination In JavaScript

This blog is about discussing and creating simple pagination in JavaScript. Pagination is, in simple terms means to navigate among the links in the pages. We often see them whenever we visit a website that has a learning topic where you have many topics and you want to navigate between them. It’s always useful to subdivide the content into different parts when you have to show many contents at once. Doing this will also allow the visitor to understand the topic more concisely and not hard to navigate among them. How does all this navigation work? Yes, this is what we call Pagination. So, in this tutorial, we’ll implement fully functional pagination on a web page using JavaScript.

What is Pagination in JavaScript?

In simple terms Pagination means you move from one page to another page either by clicking the Buttons or Links attached to it. The items can be as First Page, Next Page, Previous Page, and the Last Page buttons or links depending upon the site you visit. There can be various use cases of Pagination depending on the context we use them. It helps with loading data from a server and also makes information simpler to read. You may choose to only load a specific amount of items each time the user chooses to view them by using pagination. This reduces the amount of information on a page and saves time. Our project blog simple pagination in javascript covers this topic in-depth and how we can implement them.

Why use Pagination In JavaScript

First of all, we all need to understand that pagination is not used in desktop applications but its application is mostly for web pages. So as JavaScript developers it becomes extremely important for us to build a pagination system for our pages that have a huge set of data loading from the server. Doing this so will also save the time and memory of the web page. Not only this but it also increases the loading speed of the web page we visit. As we say and hear that JavaScip is the language of the Web, so it’s easier for us to create a pagination system in JavaScript.

Real-Time Scenario: Let’s take the amazon website or Flipkart website for displaying available products in their database. Let’s suppose they have 1 million products with them. If they are trying to show all the items at a time, the customer must wait more time like one day to see all the product lists. So how do we handle them all? For this, there are so many JavaScript-based jQuery library plugins available there for creating a simple pagination system with ease. We don’t even have to worry about the customization of the plugins. They are simple to use and easy to pick up. JavaScript pagination in the web pages allows us to create simple and efficient workable links.

Let’s Start Building our Pagination System

So our pagination system will have three main things. They have one HTML file for laying out the structure of the content, a CSS file for styling them beautifully, and a JavaScript file for creating the logical decision of the pagination system. Not to forget to mention that we will build a Pagination system with Pure JavaScript and with the jQuery library.

Pagination with jQuery Library

At first, we will be using the jQuery library for creating the simple pagination in JavaScript. We will use the smile pagination plugin available in jQuery. So let’s build the project. Here is the look of the final product.

pagination in javascript
pagination in javascript

1. Initialize the HTML structure

Let us create an index.html file and place our content there for the structural layout. For this demo project, we are using HTML for our content but in real-case scenarios, the data may come through the JSON server which needs to be handled with JavaScript.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pagination In JavaScript</title>
  </head>
  <body>
    <div class="list-wrapper">
      <div class="list-item">
        <h4>Iron Man</h4>
        <p>
          Iron Man is a 2008 American superhero film based on the Marvel Comics
          character of the same name, produced by Marvel Studios and distributed
          by Paramount Pictures. It is the first film in the Marvel Cinematic
          Universe (MCU). The film was directed by Jon Favreau, with a
          screenplay by the writing teams of Mark Fergus ...
        </p>
      </div>
      <div class="list-item">
        <h4>The Incredible Hulk</h4>
        <p>
          The Incredible Hulk is a 2008 American superhero film based on the
          Marvel Comics character the Hulk, produced by Marvel Studios and
          distributed by Universal Pictures. It is the second film in the Marvel
          Cinematic Universe (MCU). The film was directed by Louis Leterrier,
          with a screenplay by Zak Penn. It stars Edward ...
        </p>
      </div>
      <div class="list-item">
        <h4>Iron Man 2</h4>
        <p>
          Iron Man 2 is a 2010 American superhero film based on the Marvel
          Comics character Iron Man, produced by Marvel Studios and distributed
          by Paramount Pictures. It is the sequel to 2008's Iron Man, and is the
          third film in the Marvel Cinematic Universe (MCU). Directed by Jon
          Favreau and written by Justin Theroux, the film ...
        </p>
      </div>

      <div class="list-item">
        <h4>Thor</h4>
        <p>
          Thor is a 2011 American superhero film based on the Marvel Comics
          character of the same name, produced by Marvel Studios and distributed
          by Paramount Pictures. It is the fourth film in the Marvel Cinematic
          Universe (MCU). The film was directed by Kenneth Branagh, written by
          the writing team of Ashley Edward Miller ...
        </p>
      </div>
      <div class="list-item">
        <h4>Captain America: The First Avenger</h4>
        <p>
          Captain America: The First Avenger is a 2011 American superhero film
          based on the Marvel Comics character Captain America, produced by
          Marvel Studios and distributed by Paramount Pictures. It is the fifth
          film in the Marvel Cinematic Universe (MCU). The film was directed by
          Joe Johnston, written by the writing team of ...
        </p>
      </div>
      <div class="list-item">
        <h4>The Avengers</h4>
        <p>
          Marvel's The Avengers or simply The Avengers, is a 2012 American
          superhero film based on the Marvel Comics superhero team of the same
          name, produced by Marvel Studios and distributed by Walt Disney
          Studios Motion Pictures. It is the sixth film in the Marvel Cinematic
          Universe (MCU). The film was written and ...
        </p>
      </div>
      <div class="list-item">
        <h4>Iron Man 3</h4>
        <p>
          Iron Man 3 is a 2013 American superhero film based on the Marvel
          Comics character Iron Man, produced by Marvel Studios and distributed
          by Walt Disney Studios Motion Pictures. It is the sequel to 2008's
          Iron Man and 2010's Iron Man 2, and the seventh film in the Marvel
          Cinematic Universe (MCU). The film was directed ...
        </p>
      </div>
      <div class="list-item">
        <h4>Thor: The Dark World</h4>
        <p>
          Thor: The Dark World is a 2013 American superhero film based on the
          Marvel Comics character Thor, produced by Marvel Studios and
          distributed by Walt Disney Studios Motion Pictures. It is the sequel
          to 2011's Thor and the eighth film in the Marvel Cinematic Universe
          (MCU). The film was directed by Alan Taylor, with a ...
        </p>
      </div>
      <div class="list-item">
        <h4>Captain America: The Winter Soldier</h4>
        <p>
          Captain America: The Winter Soldier is a 2014 American superhero film
          based on the Marvel Comics character Captain America, produced by
          Marvel Studios and distributed by Walt Disney Studios Motion Pictures.
          It is the sequel to 2011's Captain America: The First Avenger and the
          ninth film in the Marvel Cinematic ...
        </p>
      </div>
      <div class="list-item">
        <h4>Guardians of the Galaxy</h4>
        <p>
          Guardians of the Galaxy is a 2014 American superhero film based on the
          Marvel Comics superhero team of the same name, produced by Marvel
          Studios and distributed by Walt Disney Studios Motion Pictures. It is
          the tenth film in the Marvel Cinematic Universe (MCU). The film was
          directed by James Gunn, who wrote the ...
        </p>
      </div>
      <div class="list-item">
        <h4>Avengers: Age of Ultron</h4>
        <p>
          Avengers: Age of Ultron is a 2015 American superhero film based on the
          Marvel Comics superhero team the Avengers, produced by Marvel Studios
          and distributed by Walt Disney Studios Motion Pictures. It is the
          sequel to 2012's The Avengers and the eleventh film in the Marvel
          Cinematic Universe (MCU). The film was ...
        </p>
      </div>
      <div class="list-item">
        <h4>Ant-Man</h4>
        <p>
          Ant-Man is a 2015 American superhero film based on the Marvel Comics
          characters of the same name: Scott Lang and Hank Pym. Produced by
          Marvel Studios and distributed by Walt Disney Studios Motion Pictures,
          it is the twelfth film in the Marvel Cinematic Universe (MCU). The
          film was directed by Peyton Reed, with a ...
        </p>
      </div>
      <div class="list-item">
        <h4>Captain America: Civil War</h4>
        <p>
          Captain America: Civil War is a 2016 American superhero film based on
          the Marvel Comics character Captain America, produced by Marvel
          Studios and distributed by Walt Disney Studios Motion Pictures. It is
          the thirteenth film in the Marvel Cinematic Universe (MCU), and the
          sequel to 2011's Captain America: The First ...
        </p>
      </div>
      <div class="list-item">
        <h4>Doctor Strange</h4>
        <p>
          Doctor Strange is a 2016 American superhero film based on the Marvel
          Comics character of the same name, produced by Marvel Studios and
          distributed by Walt Disney Studios Motion Pictures. It is the
          fourteenth film in the Marvel Cinematic Universe (MCU). The film was
          directed by Scott Derrickson, who wrote it with Jon ...
        </p>
      </div>
      <div class="list-item">
        <h4>Spider-Man: Homecoming</h4>
        <p>
          Spider-Man: Homecoming is a 2017 American superhero film based on the
          Marvel Comics character Spider-Man, co-produced by Columbia Pictures
          and Marvel Studios, and distributed by Sony Pictures Releasing. It is
          the second Spider-Man film reboot and the sixteenth film in the Marvel
          Cinematic Universe (MCU).
        </p>
      </div>
      <div class="list-item">
        <h4>Guardians of the Galaxy Vol. 2</h4>
        <p>
          Guardians of the Galaxy Vol. 2 is a 2017 American superhero film based
          on the Marvel Comics superhero team Guardians of the Galaxy, produced
          by Marvel Studios and distributed by Walt Disney Studios Motion
          Pictures. It is the sequel to 2014's Guardians of the Galaxy and the
          fifteenth film in the Marvel Cinematic ...
        </p>
      </div>
      <div class="list-item">
        <h4>Thor: Ragnarok</h4>
        <p>
          Thor: Ragnarok is a 2017 American superhero film based on the Marvel
          Comics character Thor, produced by Marvel Studios and distributed by
          Walt Disney Studios Motion Pictures. It is the sequel to 2011's Thor
          and 2013's Thor: The Dark World, and is the seventeenth film in the
          Marvel Cinematic Universe (MCU). The film ...
        </p>
      </div>
      <div class="list-item">
        <h4>Black Panther</h4>
        <p>
          Black Panther is a 2018 American superhero film based on the Marvel
          Comics character of the same name. Produced by Marvel Studios and
          distributed by Walt Disney Studios Motion Pictures, it is the
          eighteenth film in the Marvel Cinematic Universe (MCU). The film is
          directed by Ryan Coogler, who co-wrote the ...
        </p>
      </div>
      <div class="list-item">
        <h4>Avengers: Infinity War</h4>
        <p>
          Avengers: Infinity War is a 2018 American superhero film based on the
          Marvel Comics superhero team the Avengers, produced by Marvel Studios
          and distributed by Walt Disney Studios Motion Pictures. It is the
          nineteenth film in the Marvel Cinematic Universe (MCU). It is the
          sequel to 2012's The Avengers and 2015's ...
        </p>
      </div>
    </div>

    <div id="pagination-container"></div>
  </body>
</html>

So if you look at the structure, you can see the different list items that acts as our mock data. Below there is a div container with id of "pagination-container", this is where our pagination logic will be applied with jQuery plugin. The pagination containers can be seen empty becasues we will fill them with javascript logic later in the section.

2. Styling our CSS

Now let us style our HTML file and make it more attractive looking. It will simple and minimalistic design for our page. Place the pagination container at the bottom of the page, override the default button styling for the pagination number, and set a active class to show which page number is currently selected:

body {
  font-family: "Roboto", sans-serif;
  font-size: 14px;
  line-height: 18px;
  background: #f4f4f4;
}

.list-wrapper {
  padding: 15px;
  overflow: hidden;
}

.list-item {
  border: 1px solid #eee;
  background: #fff;
  margin-bottom: 10px;
  padding: 10px;
  box-shadow: 0px 0px 10px 0px #eee;
}

.list-item h4 {
  color: #ff7182;
  font-size: 18px;
  margin: 0 0 5px;
}

.list-item p {
  margin: 0;
}

.simple-pagination ul {
  margin: 0 0 20px;
  padding: 0;
  list-style: none;
  text-align: center;
}

.simple-pagination li {
  display: inline-block;
  margin-right: 5px;
}

.simple-pagination li a,
.simple-pagination li span {
  color: #666;
  padding: 5px 10px;
  text-decoration: none;
  border: 1px solid #eee;
  background-color: #fff;
  box-shadow: 0px 0px 10px 0px #eee;
}

.simple-pagination .current {
  color: #fff;
  background-color: #ff7182;
  border-color: #ff7182;
}

.simple-pagination .prev.current,
.simple-pagination .next.current {
  background: #e04e60;
}
3. Applying the JavaScript Logic

Now here comes the main part of our application, i.e. the logical application of a pagination system. How this is all going to work is simple.

  • We will only display a specific number of items on each page
  • Displaying the page numbers based on how many times the total items are broken down
  • When there is a click action on a page number it changes the display to that page
  • Allow navigating to previous and next pages
// jQuery Plugin: http://flaviusmatis.github.io/simplePagination.js/

var items = $(".list-wrapper .list-item");
var numItems = items.length;
var perPage = 4;

items.slice(perPage).hide();

$("#pagination-container").pagination({
  items: numItems,
  itemsOnPage: perPage,
  prevText: "&laquo;",
  nextText: "&raquo;",
  onPageClick: function (pageNumber) {
    var showFrom = perPage * (pageNumber - 1);
    var showTo = showFrom + perPage;
    items.hide().slice(showFrom, showTo).show();
  },
});
So here you can see the JavaScript function that creates the logic for navigation in the page. We have targeted the pagination-container id from the HTML file and access it in the js file. Then we are creating a variable that allows view only 4 contents per page hiding the rest.

Now it’s time with pure JavaScript.

Pagination With Vanilla JavaScript

In this section, we will totally use pure JavaScript or say raw JS to achieve our task. So no libraries and plugins this time. As usual as above, we will start with our three files. Here is what our final product looks like.

pagination in javascript
pagination in javascript
1. Placing the HTML File

Here we will as usual create an HTML file and fill the content with some mock data to satisfy our needs. You can use the JSON server data instead of this mock file if you are creating pagination in javascript then.

First of all, we will be defining our paginated content as a list below:

<main>

  <h1>Pagination with Vanilla JavaScript</h1>
  <ul id="paginated-list" data-current-page="1" aria-live="polite">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
    <li>Item 9</li>
    <li>Item 10</li>
    <li>Item 11</li>
    <li>Item 12</li>
    <li>Item 13</li>
    <li>Item 14</li>
    <li>Item 15</li>
    <li>Item 16</li>
    <li>Item 17</li>
    <li>Item 18</li>
    <li>Item 19</li>
    <li>Item 20</li>
    <li>Item 21</li>
    <li>Item 22</li>
    <li>Item 23</li>
    <li>Item 24</li>
    <li>Item 25</li>
    <li>Item 26</li>
    <li>Item 27</li>
    <li>Item 28</li>
    <li>Item 29</li>
    <li>Item 30</li>
    <li>Item 31</li>
    <li>Item 32</li>
    <li>Item 33</li>
    <li>Item 34</li>
    <li>Item 35</li>
    <li>Item 36</li>
    <li>Item 37</li>
    <li>Item 38</li>
    <li>Item 39</li>
    <li>Item 40</li>
    <li>Item 41</li>
    <li>Item 42</li>
    <li>Item 43</li>
    <li>Item 44</li>
    <li>Item 45</li>
    <li>Item 46</li>
    <li>Item 47</li>
    <li>Item 48</li>
    <li>Item 49</li>
    <li>Item 50</li>
  </ul>

  <nav class="pagination-container">
    <button class="pagination-button" id="prev-button" aria-label="Previous page" title="Previous page">
      &lt;
    </button>

    <div id="pagination-numbers">

    </div>

    <button class="pagination-button" id="next-button" aria-label="Next page" title="Next page">
      &gt;
    </button>
  </nav>
</main>

<footer>
 <a href="https://getsourcecode.in" target="_blank" rel="noopener">GSC</a> <span class="heart">&hearts;</span>
</footer>

We use the aria-live property so assistive technologies know when the content in this region has been updated and announce the new content to the reader.

Now upon breaking the above HTML file we can see a clear picture of our content placement. First, we created our paginated content list.

<ul id="paginated-list" aria-live="polite">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  ...
</ul>

Then in the second part, we initialized the navigation section with nav with the next page and prev page buttons and the pagination numbers container:

<nav class="pagination-container">
  <button class="pagination-button" id="prev-button" title="Previous page" aria-label="Previous page">
    &lt;
  </button>
   
  <div id="pagination-numbers">
 
  </div>
   
  <button class="pagination-button" id="next-button" title="Next page" aria-label="Next page">
    &gt;
  </button>
</nav>

Our next task as above is styling our content.

2. CSS

Our CSS approach for this will also be the same as above. Simple and minimalistic and easy to understand. Place the pagination container at the bottom of the page, override the default button styling for the pagination number, and set an active class to show which page number is currently selected:

@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');

body {
  font-family: 'Inter', sans-serif;
  line-height: 1.7;
  font-size: 1.1rem;
  margin: 0;
  color: #27253d;
  background: #e6f3f8;
}

main {
  position: relative;
  padding: 1rem 1rem 3rem;
  min-height: calc(100vh - 4rem);
}

h1 {
  margin-top: 0;
}

.hidden {
  display: none;
}

.pagination-container {
  width: calc(100% - 2rem);
  display: flex;
  align-items: center;
  position: absolute;
  bottom: 0;
  padding: 1rem 0;
  justify-content: center;
}

.pagination-number,
.pagination-button{
  font-size: 1.1rem;
  background-color: transparent;
  border: none;
  margin: 0.25rem 0.25rem;
  cursor: pointer;
  height: 2.5rem;
  width: 2.5rem;
  border-radius: .2rem;
}

.pagination-number:hover,
.pagination-button:not(.disabled):hover {
  background: #fff;
}

.pagination-number.active {
  color: #fff;
  background: #0085b6;
}

footer {
  padding: 1em;
  text-align: center;
  background-color: #FFDFB9;
}

footer a {
  color: inherit;
  text-decoration: none;
}

footer .heart {
  color: #DC143C;
}

Then again, we’ve added some simple styles, but we make sure it doesn’t apply to the disabled buttons by using the:not() selector.

3. JavaScript Logic

Now here comes the main part of our application, i.e. the logical application of a pagination system. How this is all going to work is simple.

  • We will only display a specific number of items on each page
  • Displaying the page numbers based on how many times the total items are broken down
  • When there is a click action on a page number it changes the display to that page
  • Allow navigating to previous and next pages
const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("li");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");

Next, we’ll define our global variables:

  • paginationLimit: it shows how many items we can display on each page; and
  • pageCount: shows how many pages there will be based on the pagination limit.
  • currentPage: store the value of the currentPage

We can calculate the pageCount by dividing the total number of items (listItems.length) by the paginationLimit and rounding to the highest whole number using the Math.ceil function.

Therefore, our page count will be 50/10 = 5 pages if we have 50 things and only want to display 10 items on each page. The page count will be 55/10 = 5.5, which rounds up to 6 pages if we have 55 items and wish to display 10 of them on each page.

const paginationLimit = 10;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage;
Adding Page Numbers To Pagination System

We can construct a method to generate a new button for the page number now that we know how many pages we’ll need, and then add the buttons to the pagination numbers container.

const appendPageNumber = (index) => {
  const pageNumber = document.createElement("button");
  pageNumber.className = "pagination-number";
  pageNumber.innerHTML = index;
  pageNumber.setAttribute("page-index", index);
  pageNumber.setAttribute("aria-label", "Page " + index);
 
  paginationNumbers.appendChild(pageNumber);
};
 
const getPaginationNumbers = () => {
  for (let i = 1; i <= pageCount; i++) {
    appendPageNumber(i);
  }
};

And then we’ll call the getPaginationNumbers function when the web page loads using the window.load() event:

window.addEventListener("load", () => {  getPaginationNumbers();});
Displaying our Active Pages

So now we only want to display the number of items on our page as per the paginationLimit function.

Set the value of the currentPage variable to the pageNum value:

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;
};

Get the item range that will be shown. We want to display items 1 through 10 if we’re on page 1. (according to the paginationLimit). Items 11 through 20 and so on should be displayed if we are on page 2.

const setCurrentPage = (pageNum) => {  currentPage = pageNum;    const prevRange = (pageNum - 1) * paginationLimit;  const currRange = pageNum * paginationLimit;};

Let’s loop through the items we want to display and hide the rest items. Then we will unhide all the items that fall within the range.

Note: since we’re working with arrays, item 1 will be at 0 and item 10 will be at position 9 so our logic looks like this:

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;
   
  const prevRange = (pageNum - 1) * paginationLimit;
  const currRange = pageNum * paginationLimit;
 
  listItems.forEach((item, index) => {
    item.classList.add("hidden");
    if (index >= prevRange && index < currRange) {
      item.classList.remove("hidden");
    }
  });
};

The reason we are doing this is just to hide the HTML content. If we were trying to append content from a JSON object to the DOM, we could update the logic to look something like this:

jsonData.forEach((item, index) => {  elementContainer.innerHTML = ''  if(index >= prevRange && index < currRange) {    elementContainer.appendChild(item)  }});

If we update the window.load() event, then we can set the current page as page 1 once the webpage loads:

window.addEventListener("load", () => {
  getPaginationNumbers();
  setCurrentPage(1);
});
Add Page Number Buttons Event Listener

Let us use a click event listener to trigger the setCurrentPage function whenever a page number button is clicked. Place this function inside the window.load() an event so now the function looks like this:

window.addEventListener("load", () => {
  getPaginationNumbers();
  setCurrentPage(1);
 
  document.querySelectorAll(".pagination-number").forEach((button) => {
    const pageIndex = Number(button.getAttribute("page-index"));
 
    if (pageIndex) {
      button.addEventListener("click", () => {
        setCurrentPage(pageIndex);
      });
    }
  });
});
Set Active Page Number

Additionally, we need to construct a method that appends the current class to the page number that was just selected. By deleting the current class, all buttons on the page are reset. The active class is then added to the button if its page index matches a global variable called currentPage.

const handleActivePageNumber = () => {
  document.querySelectorAll(".pagination-number").forEach((button) => {
    button.classList.remove("active");
     
    const pageIndex = Number(button.getAttribute("page-index"));
    if (pageIndex == currentPage) {
      button.classList.add("active");
    }
  });
};

Add the following code to the set current page method so that each time a new page is set, the active page number is updated:

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;
   
  handleActivePageNumber();
 
  const prevRange = (pageNum - 1) * paginationLimit;
  const currRange = pageNum * paginationLimit;
 
  listItems.forEach((item, index) => {
    item.classList.add("hidden");
    if (index >= prevRange && index < currRange) {
      item.classList.remove("hidden");
    }
  });
};

Next and Previous Buttons

Let’s extend this functionality so that it can include the next and previous buttons. We can use the same strategy in the setCurrentPage() function, and update the logic:

  • for the previous button, we can change the page using setCurrentPage(currentPage - 1)
  • And for the next button, we can change the page using setCurrentPage(currentPage + 1)

Include the event listeners for next and previous buttons in window.load():

window.addEventListener("load", () => {
  getPaginationNumbers();
  setCurrentPage(1);
 
  prevButton.addEventListener("click", () => {
    setCurrentPage(currentPage - 1);
  });
 
  nextButton.addEventListener("click", () => {
    setCurrentPage(currentPage + 1);
  });
 
  document.querySelectorAll(".pagination-number").forEach((button) => {
    const pageIndex = Number(button.getAttribute("page-index"));
 
    if (pageIndex) {
      button.addEventListener("click", () => {
        setCurrentPage(pageIndex);
      });
    }
  });
});

Disable Page Navigation Buttons

We also want to include a disabling feature on the next and previous buttons. 

  • disable the previous button if we’re on the first page (if the current page is 1)
  • disable the next button if we’re on the last page (if the current page is the total number of pages)
const disableButton = (button) => {
  button.classList.add("disabled");
  button.setAttribute("disabled", true);
};
 
const enableButton = (button) => {
  button.classList.remove("disabled");
  button.removeAttribute("disabled");
};
 
const handlePageButtonsStatus = () => {
  if (currentPage === 1) {
    disableButton(prevButton);
  } else {
    enableButton(prevButton);
  }
 
  if (pageCount === currentPage) {
    disableButton(nextButton);
  } else {
    enableButton(nextButton);
  }
};

Finally, let us pass the handlePageButtonsStatus() function into the setCurrentPage() function so that we can check the navigation every time a new page is clicked:

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;
 
  handleActivePageNumber();
  handlePageButtonsStatus();
   
  const prevRange = (pageNum - 1) * paginationLimit;
  const currRange = pageNum * paginationLimit;
 
  listItems.forEach((item, index) => {
    item.classList.add("hidden");
    if (index >= prevRange && index < currRange) {
      item.classList.remove("hidden");
    }
  });
};

Final JavaScript Code

const paginationNumbers = document.getElementById("pagination-numbers");
const paginatedList = document.getElementById("paginated-list");
const listItems = paginatedList.querySelectorAll("li");
const nextButton = document.getElementById("next-button");
const prevButton = document.getElementById("prev-button");

const paginationLimit = 10;
const pageCount = Math.ceil(listItems.length / paginationLimit);
let currentPage = 1;

const disableButton = (button) => {
  button.classList.add("disabled");
  button.setAttribute("disabled", true);
};

const enableButton = (button) => {
  button.classList.remove("disabled");
  button.removeAttribute("disabled");
};

const handlePageButtonsStatus = () => {
  if (currentPage === 1) {
    disableButton(prevButton);
  } else {
    enableButton(prevButton);
  }

  if (pageCount === currentPage) {
    disableButton(nextButton);
  } else {
    enableButton(nextButton);
  }
};

const handleActivePageNumber = () => {
  document.querySelectorAll(".pagination-number").forEach((button) => {
    button.classList.remove("active");
    const pageIndex = Number(button.getAttribute("page-index"));
    if (pageIndex == currentPage) {
      button.classList.add("active");
    }
  });
};

const appendPageNumber = (index) => {
  const pageNumber = document.createElement("button");
  pageNumber.className = "pagination-number";
  pageNumber.innerHTML = index;
  pageNumber.setAttribute("page-index", index);
  pageNumber.setAttribute("aria-label", "Page " + index);

  paginationNumbers.appendChild(pageNumber);
};

const getPaginationNumbers = () => {
  for (let i = 1; i <= pageCount; i++) {
    appendPageNumber(i);
  }
};

const setCurrentPage = (pageNum) => {
  currentPage = pageNum;

  handleActivePageNumber();
  handlePageButtonsStatus();
  
  const prevRange = (pageNum - 1) * paginationLimit;
  const currRange = pageNum * paginationLimit;

  listItems.forEach((item, index) => {
    item.classList.add("hidden");
    if (index >= prevRange && index < currRange) {
      item.classList.remove("hidden");
    }
  });
};

window.addEventListener("load", () => {
  getPaginationNumbers();
  setCurrentPage(1);

  prevButton.addEventListener("click", () => {
    setCurrentPage(currentPage - 1);
  });

  nextButton.addEventListener("click", () => {
    setCurrentPage(currentPage + 1);
  });

  document.querySelectorAll(".pagination-number").forEach((button) => {
    const pageIndex = Number(button.getAttribute("page-index"));

    if (pageIndex) {
      button.addEventListener("click", () => {
        setCurrentPage(pageIndex);
      });
    }
  });
});

Conclusion

That’s it, there it is, simple pagination in javascript with source code for you. This tutorial almost covers some of the basics of the JavaScript Pagination concepts. Whenever you have given an interview as a frontend developer or say JavaScript developer it is obvious that you have been asked to create a simple pagination system. So not from only a studying perspective but also from the practical field, it is necessary to understand pagination.

FAQ

JavaScript is one of the most popular programming languages in the market. Its rise in the developer community is significant and outstanding. When you are working on a web application then JavaScript is most for you. Hey, just do not delimit the potential of the JavaScript Programming Language as a web-specific language. With the introduction of many new frameworks and libraries, JavaScript has got some firepower to its armory. Click here to learn more about the trending javascript frameworks you need to learn.

As a Software Engineer and Developer, you are in the everchanging and frequent updating industry. Meaning that you just cannot rely on one specific programming language to sustain your work activity. You may need to learn some new technical stacks out there to meet the industry's needs/demands. While there are many programming language options out there, you can choose JavaScript as one of them to learn. Why so? Because it is one of the most popular ones and is in demand in the technical industry. Not only this but it's quite easy to learn also, I guess 😂. Mostly it also pays well. Actually it has been seen that a JavaScript developer is highly paid than most of the other languages out there. So why not not learn that pays you more. Moreover JavaScript is everywhere.

In simple terms Pagination means you move from one page to another page either by clicking the Buttons or Links attached to it. The items can be as First Page, Next Page, Previous Page, and the Last Page buttons or links depending upon the site you visit. To know more Click Here.

HTML, CSS, AND JAVASCRIPT are the basic building block of the web. Many aspiring web developers start their web development journey with them. But as a beginner, you might get confused about which projects should you build. So click the link below to find out more about building HTML CSS JavaScript projects. Click Here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.