Pagination with Javascript
Tags: html, css, javascript, webdev
Published: 2022-12-15 13:01:22

Hello Everyone , today i will show you how to create a pagination with Javascript.It is a simple pagination logic which uses array slicing.
Let's get started...


# HTML - 
```html
<div class="list-container">
<ul id="data-list"></ul>
</div>

<div class="buttons">
  <button id="prev">Prev</button>
  <input type="number" id="page-number" />
  <button id="next">Next</button>
</div>
```
* Creating a container and inside it list using ul tag and we will append the li elements inside it using javascript map() method.
* 2 buttons for next and previous navigation and 1 input for showing the current page number.

# CSS - 
```css
body{
  background-color:rgb(0,0,0,0.9);
}

.buttons{
  margin-top:100;
  display:flex;
  justify-content:center;
  gap:2rem;
}
.buttons button{
  border:none;
  padding:0.4rem 1.2rem;
  background-color:purple;
  color:white;
  border-radius:5px;
  cursor:pointer
}

#page-number{
  border:none;
  text-align:center;
  width:3rem;
  border-radius:5px;
}
#page-number:focus{
  outline:none;
}

.list-container{
  display:flex;
  justify-content:center;
}
.list-container{
  height:700px;
}
.list-container ul {
  display:grid;
  grid-template-columns:repeat(2,1fr);
  grid-template-rows:repeat(5,1fr);
  gap:1rem;
}
.list-container ul li {
  width:100px;
  height:60px;
  margin:20px 0;
  list-style:none;
  padding:0.5rem 1rem;
  background-color:slateblue;
  color:white;
  border-radius:5px;
}
```

* Some basic styling for the list and the buttons.

# Javascript - 
```js
const dataSet = [
  {
    "_id": 7703354,
    "name": "Alison Joseph"
  },
.
.
.
100 objects
];

const list = document.querySelector("#data-list");
const prevButton = document.querySelector("#prev");
const nextButton = document.querySelector("#next");
const pageNumberValue = document.querySelector("#page-number")

let startIndex = 0;
let endIndex = 10;
let pageNumber = 0;

pageNumberValue.value = pageNumber
```

* First I have created a dummy data array of objects which contains 100 objects as data
* Then I have imported the list container(ul),Next and previous buttons and the input field as pageNumberValue.
* Start index is the index which will be used as the start of the slicing of array and endIndex is the index which will be used as the end point of the sliced array.(dataSet.slice(startIndex,endIndex)).
* Setting the input value for the initial load as pageNumber which is 0. So, it will show 0 as the page number when the page first loads.

```js
const mapData = () => {
  const slicedData = dataSet
    .slice(startIndex, endIndex)
    .map((row) => {
      return `<li>${row.name}</li>`;
    })
    .join("");

  list.innerHTML = slicedData;
}

mapData();
```

* mapData is the function which is used to map the rows inside the list container(ul) using map() method.
* I have chained the slice method with map method meaning first slice the array using start and end index then map the row with the sliced elements only.
* Using list.innerHTML to put all the sliced rows as li elements inside the list container(ul)

```js
prevButton.addEventListener("click", () => {
  if (endIndex < 20) {
    startIndex = 0;
    endIndex = 10;
  } else {
    startIndex -= 10;
    endIndex -= 10;
    pageNumber -= 1;
  }
  pageNumberValue.value = pageNumber;
  mapData();
});
```
* I am showing only 10 items per page, so the increment/decrement will be 10 and the page number increment/decrement will be 1.
* If the previous button is clicked and the endIndex value after decrement goes below 20 , then set the startIndex to 0, endIndex to 10 meaning setting the first page with first 10 items and if the endIndex is greated than 20 then decrement both start and endIndex by 10 and pageNumber by 1.
* Then setting the new pageNumber value to the input field and calling the mapData function to update the DOM.

```js
nextButton.addEventListener("click", () => {
  if (endIndex < dataSet.length) {
    startIndex += 10;
    endIndex += 10;
    pageNumber += 1;
  }
  pageNumberValue.value = pageNumber;
  mapData();
});
```
* If the endIndex is less than the dataset length, then only increment start and end index by 10 and page number by 1.
* Then setting the new pageNumber value to the input field and calling the mapData function to update the DOM.

```js
pageNumberValue.addEventListener("change",(e) => {
  let currentPageNumber = Number.parseInt(e.target.value)
  let maxPageNumber = Math.floor(dataSet.length/10)
  if(currentPageNumber > maxPageNumber){
   currentPageNumber = maxPageNumber;
    e.target.value = value
  }
  else if(currentPageNumber < 0){
    currentPageNumber = 0;
    e.target.value = value
  }
   startIndex = currentPageNumber * 10;
   endIndex = startIndex + 10
   pageNumber = currentPageNumber
   mapData();
})
```
* Attaching an event listener the page number input field to change the page number manually by putting the number in the input field and directly jump to that page.
* Firstly i have converted the input value to integer and then checked that whether the input value is greated than maxPageNumber. Here i have divided the dataset by 10 to convert it as similar to page number value.(Suppose the dataset length is 100, so 100/10 = 10, there should be maximum 10 pages which is our maxPageNumber)
* If the currentPageNumber is greated than the maxPageNumber number,then set the currentPageNumber as the maxPageNumber
* If the currentPageNumber is less than 0 , then set the currentPageNumber to 0
* Then set the startIndex as currentPageNumber * 10 and endIndex as startIndex + 10 (suppose the page number is 5, then startIndex will 50 and endIndex will 60). Then set the pageNumber as currentPageNumber and call the mapData function to update the DOM.

# CODEPEN - 
{% codepen https://codepen.io/shubhamtiwari909/pen/LYrKPvN %}

THANK YOU FOR CHECKING THIS POST
You can contact me on -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/css-iswherehas-and-not-2afd

https://dev.to/shubhamtiwari909/theme-changer-with-html-and-css-only-4144

https://dev.to/shubhamtiwari909/swiperjs-3802

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90