What are some strategies to enhance the performance of JavaScript pagination to ensure it functions effectively for varying numbers of pages?

Currently, I am working on building Vanilla Javascript Pagination. I encountered an issue where the pagination seems to work flawlessly only when there are precisely 7 pages. If the page count exceeds or falls below 7, some minor bugs start to surface. I have been struggling to optimize my code to make it flexible and usable for any number of pages. Below is the code snippet:

<!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>Document</title>
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
      crossorigin="anonymous" />
    <link rel="stylesheet" href="./main.css" />
  </head>
  <body>
    <section class="blog-listing">
      <div class="container">
        <div class="row">
          <div class="col-6">
            <input
              type="search"
              class="inputs"
              id="searcher"
              placeholder="Search" />
            <input type="hidden" name="type" value="BLOG_POST" />
            <input type="hidden" name="type" value="LISTING_PAGE" />
          </div>
          <div class="col-6"></div>
        </div>

        <div class="row" id="blogs"></div>
        <div id="blog-pagination"></div>
        <div id="buttons"></div>
      </div>
    </section>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
      crossorigin="anonymous"></script>
    <script src="./main.js"></script>
  </body>
</html>

CSS

.blog-listing {
  padding: 200px 0px;
}
.blog-listing input {
  background-color: #f3f3f3;
  border-radius: 40.5px;
  width: 100%;
  padding: 20px;
  margin-bottom: 20px;
}
.blog-listing input::-moz-placeholder {
  font-family: "Poppins";
  font-weight: 300;
  font-size: 18px;
  line-height: 44px;
  color: #19212f;
}
.blog-listing input:-ms-input-placeholder {
  font-family: "Poppins";
  font-weight: 300;
  font-size: 18px;
  line-height: 44px;
  color: #19212f;
}
...

JS

let allBlogs = [];
allBlogs.length = 14;

// JavaScript code here...

// End of JavaScript code

https://i.sstatic.net/M3H2N.png

I've been working on optimizing the code for varying numbers of pages, but I'm facing challenges in finding an ideal solution.

Answer №1

When it comes to setting up pagination numbers and links, consider implementing the following approach:

 //Identify the element where page numbers will be displayed
 let paginationElem = document.getElementById("yourPageElementIdHere")

 //Your list of blogs
 let allBlogs = []

 //Calculate the total number of pages needed
 let pagesNeeded = allBlogs.length / <number of entries per-page> //Remember to round the number if necessary

 //Generate a clickable link for each page. Start the loop at 1 to prevent displaying the first page as "0"
 for(i=1; i < pagesNeeded + 1; i++) {
    let pageNum = document.createElement("a")
    pageNum.innerHTML = i
    pageNum.href = "" //your link to the page goes here
    paginationElem.append(pageNum)
 }

If you are wondering how to retrieve and display the relevant articles on each page, you will need to extract the page number clicked - possibly through a search param like (?pageNum=4) in the link. Then, you can create a loop to gather the appropriate articles into an array. The following snippet should help achieve this:

 //Your articles stored in an array
 let allBlogs = []

 let pageNum = //Fetch the value from the search param

 // Array to hold articles to be displayed on the selected page
 let articlesToDisplay = []

 //Set the initial value for the first page
 let firstArticle = 0

 // Determine the starting point for the loop based on the selected page
 if(pageNum != 0) {
     firstArticle = (pageNum - 1) * 10 //or other number of articles per page
 }

 // Iterate through the articles starting from the first one, and add a specified number of articles (10 in this example) to the array
 for(i=firstArticle; i < firstArticle + 10; i++) {
   articlesToDisplay.push(allBlogs[i])
 }

You can then loop through the articlesToDisplay array or generate elements within a final loop to append them to a section within the document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NodeJS making seven successful Ajax requests

I'm delving into the world of JavaScript, NodeJS, and electron with a goal to create a presenter-app for remote control over powerpoint presentations. My setup involves an electron server structured like this: const electron = require('electron ...

Is it possible to rotate an image with a random angle when hovering in Angular?

I'm currently working on a photo gallery project and my goal is to have the images rotate when hovered over. However, I am experiencing difficulties in passing values from TypeScript into the CSS. HTML <div class="back"> <div cl ...

Bidirectional updates in AngularJS with CSS styling

On the backend, certain HTML elements store their position and size persistently and retrieve them when the page loads. These elements can be dragged and resized by users, with any updates needing to be saved on the backend for consistency across sessions. ...

Filter a Vue list based on a checkbox that can be either checked or unchecked

I am currently working on my Vue app and aiming to filter a list to display only entries that have been moderated. However, I am encountering an issue where when the checkbox is checked, I receive all the results that are true, and when the checkbox is un ...

Utilizing jQuery for AJAX requests on a timed loop

I'm puzzled by a situation involving an AJAX call within an interval. It seems that the code doesn't work as expected, and I'm wondering why. Initially, I had this code snippet which wasn't functioning properly: setInterval($.ajax({ ...

Getting a product by its slug can be achieved with Next.js 14 and Sanity by utilizing the capabilities

My dilemma involves retrieving specific product details based on the current slug displayed in the browser. While I successfully retrieve all products using the following code: export async function getAllProducts() { const productData = await client.fe ...

"Rails Ajax spinner functions properly in the development environment, but encounters issues in the

I am currently implementing this JavaScript code: verify_link.js ... a=$(this).parent(); a.html('<img src="assets/ajax-loader.gif">'); ... The image file is located in app/assets/images/ajax-loader.gif Everything works fine in de ...

What is the best way to target and style anchor links in CSS that are not empty?

Hi there! I am on the hunt for a CSS selector that will target all anchor links that are not empty and contain content. I currently have a selector to identify all links with an anchor attribute, like in this example: a[href*=\#] { background-co ...

Converting JSON data into an HTML table

I'm struggling to convert a JSON object into an HTML table, but I can't seem to nail the format. DESIRED TABLE FORMAT: Last Year This Year Future Years 45423 36721 873409 CURRENT TABLE FORMAT: Last Year 45423 This ...

How can I trigger a masterpage function from a contentpage in asp.net?

I am trying to call a function on the masterpage from a content page in the codebehind. Here is my attempt: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alert__", string.Format("setStatusBarMessage('{0}',{1});", barMessage, ty ...

Divide Footer Information into Two Sections: Left and Right

<footer> <div class="copyrights-left"> <p>&copy 2015. <a style="color: #fff;" href="index.html">Free Xbox Live Gold Membership and Free Xbox Live Gold Codes</a>. All rights reserved.</p></div> <div class="co ...

Adding JSON data before the second to last element of an array:

I am looking to create a function that can consistently add JSON Items to an array just before the last item. const array = [ {India: { Score: '12', PlayedMatched: '21' } }, { China: { Score: '52', PlayedMatched: '51 ...

Onload, capture page elements, delete them, and then access the original content

I am encountering two DIV elements on my page that I need to capture upon loading the page and preserve their contents until the page is refreshed. The nested DIV element is contained within the other one. After locating these elements initially, I want t ...

The changes made to the state array in react.js are not reflected in the DOM

In my React game implementation, I have the board set up as a two-dimensional array in the initial state of the parent component. The tiles on the board are rendered by looping through this array. Each tile receives a function as a prop that allows it to m ...

Is it a suboptimal method to repeatedly use order.find, collect data, and transmit a substantial data payload to the front end in

Currently, I am working with Express, React, and MongoDB but I am relatively new to using express and REST API. My goal is to add an analytics feature to my frontend that focuses on sales and orders. The plan is to allow users to search within a specified ...

Implement dynamic configuration injection by allowing users to specify the name of a configuration file during runtime, instead of having it fixed in the code

In my development using webpack, I am exploring ways to make my application configurations more dynamic. Presently, the project is a create-react-app that has been ejected. For instance, when creating a local build in my package.json file, I include the f ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

The Americanpurpose1 font family features playful smiley faces when special characters such as parentheses and hashtags are used

I have utilized the font family americanpurpose1 for my current project, however, I am encountering issues where special characters such as (), #, etc. are displaying as Smiley faces. I have attempted to use HTML symbol codes to resolve this problem, but u ...

Greetings! Unable to retrieve data within the TRY block following the resolution of an error in another function

Consider the following code snippet: const axios = require('axios'); const cheerio = require('cheerio'); let data = null; const parseNewCorporations = async (iter) => { let link2 = 'https://www.finanzen.net/aktien/' + ...

What is the process of sending a file to a server and storing it in a MySQL database?

Currently, I am exploring the process of enabling users to upload images of specific dimensions (468px by 60px) to a designated directory on my server, such as example.com/banners. Subsequently, the URL link to these uploaded banners will be stored in a ...