Pagination_javascript_machine_coding

Implement Pagination In Vanilla JavaScript

Hi friends, we will implement pagination in the core vanilla Javascript in this article. It is one of the most crucial questions in the interview for machine coding. Although if we look around, many Javascript libraries and implementations are available, making this task very easy. But implementing it in core Javascript will strengthen our core language concept.

How Pagination Works

In this section will try to understand how the pagination core concept works and why it is needed. Pagination work on the principle of showing certain pages in one view. For example, we have 10 thousand records to display. If we show all the data in one-page load, it will take so much time to load the page, and eventually, the website will become slow, and the user will leave the website.
As we know, the data is increasing due to all the work going online or digitalized.

First, we will understand the core concept of pagination in step by step manner.

  1. In the first step, we will load only limited data on the website. For example, we have 10 thousand data, but we will load only 50 data sets.
  2. In the second step, we will load the navigation tool where the user can navigate to the desired pages per the requirement.
  3. In the third step, for example, the user has clicked the 6th link in the navigation on the click of that user can fire an API in which we will provide the offset and limit. Based on the data return, we will display it on the webpage.

Set Up the HTML

In this step, we will first set up the HTML page for the pagination.

<!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 Practice</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div class="page-container">
        <div>Pagination Using Vanilla Javascript</div>
        <div class="data_block" id="data-block">
            
        </div>
        <div class="pagination-block">
            <button class="pag-button" id="prev_page">Prev</button>
            <span id="page_number" class="flex"></span>
            <button class="pag-button" id="next_page">Next</button>
        </div>
    </div>
    <script src="index.js"></script>
</body>
</html>
  1. We have created the container in which all the HTML code will come.
  2. We have added the link to our style sheet(CSS) and script file, in which we will write our main logic.

Set up the style sheet(CSS) file

In this section, we have just added the simple CSS to display the data in a simpler view, not any fancy CSS 🙂

body{
    padding: 0;
    margin: 0;
}

.flex{
    display: flex;
}

.page-container{
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;
    border: 2px solid lightseagreen;
    background-color: darkseagreen;
}

.pagination-block{
    display: flex;
    flex-direction: row;
    margin-top: 20px;
}

.data-element {
    border: 2px solid white;
    width: 100px;
    text-align: center;
    background-color: whitesmoke;
    margin-top: 10px;
}

.pag-button{
    border: 1px solid black !important;
    margin-right: 5px;
    margin-left: 5px;
    cursor: pointer;
}

.page-number-row{
    background-color: lightgrey;
    padding: 5px;
    margin-left: 2px;
    margin-right: 2px;
    cursor: pointer;
}

.pagination-block button{
    border: 0;
}

.opacity {
    opacity: 0.5;
}

Main Content

In this section will add the main logic behind the pagination concept. Let’s start with step by step manner.

  1. Add the sample date we want to show in the web page
 const jsonData = [
        {
            id:1,
            title: "Data 1"
        },
        {
            id:2,
            title: "Data 2"
        },
        {
            id:3,
            title: "Data 3"
        },
        {
            id:4,
            title: "Data 4"
        },
        {
            id:5,
            title: "Data 5"
        },
        {
            id:6,
            title: "Data 6"
        },
        {
            id:7,
            title: "Data 7"
        },
        {
            id:8,
            title: "Data 8"
        },
        {
            id:9,
            title: "Data 9"
        },
        {
            id:10,
            title: "Data 10"
        },
        {
            id:11,
            title: "Data 11"
        },
        {
            id:12,
            title: "Data 12"
        },
        {
            id:13,
            title: "Data 13"
        },
        {
            id:14,
            title: "Data 14"
        },
        {
            id:15,
            title: "Data 15"
        },
        {
            id:16,
            title: "Data 16"
        },
        {
            id:17,
            title: "Data 17"
        },
        {
            id:18,
            title: "Data 18"
        },
        {
            id:19,
            title: "Data 19"
        },
        {
            id:20,
            title: "Data 20"
        },
        {
            id:21,
            title: "Data 21"
        },
        {
            id:22,
            title: "Data 22"
        },
        {
            id:23,
            title: "Data 23"
        },
        {
            id:24,
            title: "Data 24"
        },
        {
            id:25,
            title: "Data 25"
        },
        {
            id:26,
            title: "Data 26"
        },
        {
            id:27,
            title: "Data 27"
        },
        {
            id:28,
            title: "Data 28"
        },{
            id:29,
            title: "Data 29"
        },
        {
            id:30,
            title: "Data 30"
        },
        {
            id:31,
            title: "Data 31"
        },
        {
            id:32,
            title: "Data 32"
        },
        {
            id:33,
            title: "Data 33"
        },
        {
            id:34,
            title: "Data 34"
        },
        {
            id:35,
            title: "Data 35"
        },
        {
            id:36,
            title: "Data 36"
        },
        {
            id:37,
            title: "Data 37"
        },
        {
            id:38,
            title: "Data 38"
        },
        {
            id:39,
            title: "Data 39"
        },
        {
            id:40,
            title: "Data 40"
        },
        {
            id:41,
            title: "Data 41"
        }


    ]

2. In this section, we will discuss the main logic behind pagination.

(function(){
    
     
   let currentPageNumber = 1;
    const itemsPerPage = 5;
    const totalItems = jsonData.length;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    const prevPage = document.getElementById('prev_page');
    const nextPage = document.getElementById('next_page');
    const clickPage = document.getElementById('page_number');

    prevPage.addEventListener('click',prevPa);
    nextPage.addEventListener('click', nextPa);
    clickPage.addEventListener('click', clickOnPageNumber);

    function clickOnPageNumber(e){
        currentPageNumber = +e.target.innerHTML;
        initPage(+e.target.innerHTML);
    }

    function prevPa(){
        if(currentPageNumber > 1)
            initPage(--currentPageNumber);
    }

    function nextPa(){
        if(currentPageNumber < totalPages)
            initPage(++currentPageNumber);
    }

    function initPage(pageNumber){
        loadData(pageNumber);
        getAllPages(pageNumber);
        setButtonOpacity(pageNumber)

    }

    function loadData(curPage){
        let dataBlock = document.getElementById('data-block');
        
        if(curPage < 1){
            curPage = 1;
        }else if(curPage > totalPages) {
            curPage = totalPages;
        }

        dataBlock.innerHTML = '';
        for (let i = (curPage - 1) * itemsPerPage; i < (itemsPerPage * curPage) && i < jsonData.length; i++) {
            dataBlock.innerHTML += `<div class='data-element'>${jsonData[i].title}</div>`; 
        }
    }

    function getAllPages(pageNumber){
        let pageContainer = document.getElementById('page_number');
        pageContainer.innerHTML = '';
        for (let i = 1; i <= totalPages; i++) {
            let style = 'style="opacity:0.5"'
            if(i === pageNumber){
                style = 'style="opacity:1"'
            }
            pageContainer.innerHTML += `<div class='page-number-row opacity' ${style} id='page-number-row-${i}'>${i}</div>`
        }
    }

    function setButtonOpacity(pageNumber){
        if(pageNumber === 1){
            prevPage.style.opacity = 0.5;
            prevPage.style.cursor = 'default';
        }else{
            prevPage.style.opacity = 1;
            prevPage.style.cursor = 'cursor';
        }

        if(pageNumber === totalPages){
            nextPage.style.opacity = 0.5;
            nextPage.style.cursor = 'default';
        }else{
            nextPage.style.opacity = 1;
            nextPage.style.cursor = 'cursor';
        }
        
    }

    initPage(currentPageNumber); 
    

})()
  1. In the first step, we have defined the variable such as currentPageNumber, itemsPerPage, totalItems and totalPages.
  2. On page load, we have initiated the init function in which we have passed the first page as the default page number.
 initPage(currentPageNumber);

3. In the initPage function, we have called 3 functions in which first, we will load the data, set the navigation button, and in the last function, we will set the button opacity.

function initPage(pageNumber){
        loadData(pageNumber);
        getAllPages(pageNumber);
        setButtonOpacity(pageNumber)
;
    }

    function loadData(curPage){
        let dataBlock = document.getElementById('data-block');
        
        if(curPage < 1){
            curPage = 1;
        }else if(curPage > totalPages) {
            curPage = totalPages;
        }

        dataBlock.innerHTML = '';
        for (let i = (curPage - 1) * itemsPerPage; i < (itemsPerPage * curPage) && i < jsonData.length; i++) {
            dataBlock.innerHTML += `<div class='data-element'>${jsonData[i].title}</div>`; 
        }
    }

    function getAllPages(pageNumber){
        let pageContainer = document.getElementById('page_number');
        pageContainer.innerHTML = '';
        for (let i = 1; i <= totalPages; i++) {
            let style = 'style="opacity:0.5"'
            if(i === pageNumber){
                style = 'style="opacity:1"'
            }
            pageContainer.innerHTML += `<div class='page-number-row opacity' ${style} id='page-number-row-${i}'>${i}</div>`
        }
    }

    function setButtonOpacity(pageNumber){
        if(pageNumber === 1){
            prevPage.style.opacity = 0.5;
            prevPage.style.cursor = 'default';
        }else{
            prevPage.style.opacity = 1;
            prevPage.style.cursor = 'cursor';
        }

        if(pageNumber === totalPages){
            nextPage.style.opacity = 0.5;
            nextPage.style.cursor = 'default';
        }else{
            nextPage.style.opacity = 1;
            nextPage.style.cursor = 'cursor';
        }
        
    }

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

SUMMARY

In this way, we can implement the pagination with vanilla Javascript. Implementing the pagination page load will increase the sustainability of the page.

It is available in this GitHub repository if you would like to grab the source code in one piece