Frontend pagination with vanilla JavaScript

Reading Time: 3 minutes 🕑

Last updated: September 27, 2022.

Pagination can improve the load speed and performance of content by spreading it across multiple pages.

A classic example would be an image gallery with hundreds of pictures. You wouldn’t want to try and load all of those at once, especially as the user may only view a few of them.

With pagination, only a limited amount of content is loaded at first, and more content is loaded only when a user navigates to another page.

This tutorial shows you how to achieve this on the frontend, with JavaScript controlling page navigation.

By the end of the tutorial, you will be able to paginate between content like this:

Pagination project preview
Table of contents

HTML markup

The HTML necessary is very limited. All that is needed is an element in which to display content and another for navigation.

In this case, both are nested inside a wrapper element:

<div id="wrapper">
    <div id="nav"></div>
    <div id="content"></div>
</div>

Content data

The content data that will be displayed on each page should be in array format.

Each element in the array should contain all the data needed to display that item of content.

For example, here’s what we’ll be using in this tutorial:

const items = [
  {
    src: "images/1.jpg",
    desc: "Pine tree leaves",
  },
  {
    src: "images/2.jpg",
    desc: "Abandoned building",
  },
  {
    src: "images/3.jpg",
    desc: "Bible reading",
  },
  {
    src: "images/4.jpg",
    desc: "Sunny day",
  },
  {
    src: "images/5.jpg",
    desc: "Flying over the sea",
  },
  {
    src: "images/6.jpg",
    desc: "Sunset",
  },
  {
    src: "images/7.jpg",
    desc: "Clubhouse",
  },
  {
    src: "images/8.jpg",
    desc: "Suburbs",
  },
  {
    src: "images/9.jpg",
    desc: "By boat",
  },
  {
    src: "images/10.jpg",
    desc: "Laptop",
  },
];

JavaScript

First steps and configuration

Now, we are ready to program pagination with JavaScript.

To begin, select the content page and navigation elements.

Then, set an index value for the current page and a value for the number of items that should appear on each page:

const nav = document.getElementById('nav');
const content = document.getElementById('content');

let pageIndex = 0; // Page index initialized at 0
let itemsPerPage = 3; // Sets items on each page

Loading content to the page

Now, items can be loaded to the page by creating a function that iterates through the content data object, taking into account pageIndex and itemsPerPage.

The loop should start at pageIndex*itemsPerPage and finish at this value +itemsPerPage. This iterates through a page of content, starting at the page corresponding to pageIndex.

The content iterated through is then written to the DOM.

const nav = document.getElementById('nav');
const content = document.getElementById('content');
let pageIndex = 0;
let itemsPerPage = 6;
loadItems();
function loadItems() {
    content.innerHTML = "";
    for (let i=pageIndex*itemsPerPage; i<(pageIndex*itemsPerPage)+itemsPerPage; i++) {
        if (!items[i]) { break }
        const item = document.createElement('div');
        item.innerHTML = `
        <div>
            <img src="${items[i].src}"/>
        </div>
        <div>
            <span>${items[i].desc}</span>
        </div>
        `;
        content.append(item);
    }
}

Adding page navigation

To add page numbering navigation, create a new function.

Inside the function, loop through the length of items divided by itemsPerPage. This returns the number of pages.

Since JavaScript counts from 0, you will need to add 1 to the value of i to get the human-readable page number.

Each page number should be printed inside the navigation element. Each page number value is printed inside a <span> element. And for each one, an event listener is added that, when clicked, will set the value of pageIndex to itself and call the loadItems function. This is how a new page is loaded.

Also, make sure that this new loadPageNav function is called and the end of the loadItems function, so the navigation is updated each time new page content is loaded.

const nav = document.getElementById('nav');
const content = document.getElementById('content');
let pageIndex = 0;
let itemsPerPage = 6;
loadItems();
function loadItems() {
    content.innerHTML = "";
    for (let i=pageIndex*itemsPerPage; i<(pageIndex*itemsPerPage)+itemsPerPage; i++) {
        if (!items[i]) { break }
        const item = document.createElement('div');
        item.innerHTML = `
        <div>
            <img src="${items[i].src}"/>
        </div>
        <div>
            <span>${items[i].desc}</span>
        </div>
        `;
        content.append(item);
    }
    loadPageNav();
}
function loadPageNav() {
    nav.innerHTML = "";
    for (let i=0; i<(items.length/itemsPerPage); i++) {
        
        const span = document.createElement('span');
        span.innerHTML = i+1;
        span.addEventListener('click', (e) => {
            pageIndex = e.target.innerHTML-1;
            loadItems();
        });
        if (i === pageIndex) {
            span.style.fontSize = "2rem";
        }
        nav.append(span);
    }
}

And that's all you need. Now, only content on the current page will be loaded to the DOM.

Summary

Implementing frontend pagination with JavaScript decreases the amount of content loaded initially. Then, only content that is navigated to by the user is loaded.

Pagination is therefore an efficient solution to loading a large amount of data. By avoiding unnecessary loading, it can also improve user experience.