Navigating through pages using << >>, Previous, and Last buttons while preventing infinite scrolling

This particular code snippet is designed to generate a new page for every set of 8 div elements.

pageSize = 8;

showPage = function(page) {
  $('.line-content').hide();
  $('.line-content:gt('+((page-1)*pageSize)+'):lt('+(page)*(pageSize-1)+')').show();
   $('.line-content:eq('+((page-1)*pageSize)+')').show();
}

var pgs = Math.ceil($('.line-content').length/pageSize);
var pgnt = '';
  for(var i=1;i<=pgs;i++){
pgnt += '<li><a href="#">'+i+'</a></li>';
}
$('#pagin').html(pgnt);
$("#pagin li a").click(function() {
  $("#pagin li a").removeClass("current");
$(this).addClass("current");
showPage(parseInt($(this).text())) 
});
showPage(1);
.current {
  color: green;
}

#pagin li {
  display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="line-content">1 I have some content</div>
<div class="line-content">2 I have some content</div>
<div class="line-content">3 I have some content</div>
<div class="line-content">4 I have some content</div>
<div class="line-content">5 I have some content</div>
<div class="line-content">6 I have some content</div>
<div class="line-content">7 I have some content</div>
<div class="line-content">8 I have some content</div>
<div class="line-content">9 I have some content</div>
<div class="line-content">10 I have some content</div>
<div class="line-content">11 I have some content</div>
<div class="line-content">12 I have some content</div>

<ul id="pagin"></ul>

The main objective of this code is to display a paging style by creating

<li><a href></a></li>
tags for each set of 8 <Div>. However, the concern arises when too many
<li><a href></a></li>
are created exceeding the desired limit. The question then becomes how to achieve a pagination layout resembling:

<< Prev 1 2 3 4 5 6 7 8 Next >>

The aim is to have at least 8 containers on a page, adjusting the number of pages if it falls below 1. Additionally, incorporating features such as Prev, Next, and even << >> for user-friendly navigation.

Thank you in advance for any assistance provided.

Answer №1

Perhaps this is what you are looking for. Take a look at the following code snippet:
(working fiddle: https://jsfiddle.net/whp1uhfo/)

pageSize = 8;
current_page = 1;

var pgs = Math.ceil($('.line-content').length / pageSize);
var pgnt = '<li><span id="prev" onclick="showPage(current_page - 1)"> &lt;&lt; Prev</span>';

showPage = function(page) {
  $('.line-content').hide();
  $('.line-content:gt(' + ((page-1)*pageSize) + '):lt(' + (page)*(pageSize-1) + ')').show();
  $('.line-content:eq(' + ((page-1)*pageSize) + ')').show();
  current_page = page;
  
  if(page == pgs){
    $('#next').hide();
  } else {
    $('#next').show();
  }
  
  if(page == 1){
    $('#prev').hide();
  } else {
    $('#prev').show();
  }
}

for(var i=1; i<=pgs; i++){
  pgnt += '<li><a href="#">' + i + '</a> </li> ';
}

pgnt += '<li><span id="next" onclick="showPage(current_page + 1)">Next &gt;&gt;</span>';

$('#pagin').html(pgnt);
$("#pagin li a").click(function() {
  $("#pagin li a").removeClass("current");
  $(this).addClass("current");
  showPage(parseInt($(this).text())) 
});
showPage(1);

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

Different ways to determine if a given string exists within an Object

I have an object called menu which is of the type IMenu. let menu: IMenu[] = [ {restaurant : "KFC", dish:[{name: "burger", price: "1$"}, {name: "french fries", price: "2$"}, {name: "hot dog", d ...

Modify the data in a JSON array and receive the revised array using JavaScript

Within my JSON object, I have price values in numerical format. I am looking to convert these price values into strings within the same object My approach involves using the map function: var prods = [ { "id": "id-1", "price": 239000, "inf ...

Receiving alerts as soon as the page DOM is fully loaded, prior to the window.onload event

Is there a consistent way to get notified when the page body has loaded across all browsers, regardless of differences in implementation? Here are some methods I'm aware of: DOMContentLoaded: Supported in Mozilla, Opera 9, and newer WebKits. This i ...

A guide to validating a pair of fields within a single object using React hooks and the Yup library

{ label: 'Room', name: 'room', rule: yup.array(yup.object()).required(), renderer: (data: any) => { const { control, register, errors } = useFormContext(); return ( ...

Having trouble inputting text into input field using ReactJS

I am currently facing a challenge while attempting to modify the value of an input field using ReactJS. The issue I am encountering is the inability to input values into the field. After reviewing several other queries, it appears that simply changing the ...

Collision Detection within a THREE.Group in Three.js

Currently, I am tackling the challenge of detecting 3D AABB collisions between a box and a sphere. An interesting observation: when a box is directly added to the scene, collisions are detected successfully. However, when the box is added to a group (THRE ...

I am receiving a Promise object with a status of "pending" within an asynchronous function on node.js

I have a nodejs class function that retrieves all rows from the database. module.exports = class fooClass { static async fooFunc() { const mysql = require('mysql'); const util = require('util'); const conn = mysql.createC ...

What is the most efficient way to accelerate the process of creating jQuery UI Dialogs for a vast quantity of HTML

I am faced with a situation where I have a table containing a large amount of HTML and I'm attempting to set up a jQuery dialog for it. However, the process is extremely slow (taking about 8 seconds in Internet Explorer), which is not acceptable. Typi ...

Hover over or click to automatically focus on the input field

I have an icon that triggers focus on an input field when hovered over. I also want the same functionality to occur when the user clicks on the icon. if(!mobile){ $('#search-icon').hover( function(){ if($('.sear ...

Interactive Tab content display

I'm working on a tabs component and I need Angular to only render and initialize the active tab instead of all tabs. Is there a way to achieve this? <my-tabs> <my-tab [tabTitle]="'Tab1'"> <some-component></some-co ...

The Content-Type header is missing in the Ajax request for json

In my PHP code, I generate valid JSON and set the content-type header to application/json in my development environment. However, when I deploy this code to an embedded web server, it functions properly but is unable to send the appropriate content-type he ...

I am experiencing an issue with my d3 force directed graph where the links are not

I am relatively new to d3 and have limited experience with web frontend development. In my current web application project, I am attempting to create a force directed graph. Despite spending several hours trying to make it work, I have been unable to displ ...

Is there a way to prevent my Header links from wrapping during window size testing?

https://i.stack.imgur.com/YTc3F.png The image above showcases my standard header layout, while the one below illustrates what occurs as I resize the window. https://i.stack.imgur.com/re44T.png Is there a specific CSS solution to prevent the Text navLink ...

Modifying text appearance and design in material-ui release 0.15.4

I'm quite new to CSS and front-end web development, and I'm struggling with setting the style of a button on my page. I want to change the text color and possibly adjust the primary color of my theme from cyan to blue. I know that material-ui has ...

Scale first, then drag and drop to fix a faulty registration

I'm currently working on a project that involves dragging and dropping the correct items onto a technical drawing, such as a motherboard. The user is presented with pictures of components like CPUs or DDR memory and must drag these items to their corr ...

Utilizing selected Bootstrap dropdown option for extracting value

I'm currently learning about development and am trying to create a bootstrap dropdown with 3 different background image options. My goal is to change the background based on the selected option from the dropdown. However, I am struggling to figure out ...

Is there a way to turn off the auto-complete feature for JavaScript keywords in HTML within JSX in WebStorm?

While using WebStorm, I've noticed that it automatically completes JavaScript keywords as I type regular text in JSX. This behavior is starting to frustrate me because I have to constantly press ESC or click elsewhere to hide the auto-complete popup. ...

What are the steps to separate Bootstrap 5 from other frameworks?

Is there a way to apply bootstrap-5 styles only to a specific block or page? Can someone provide guidance on isolating bootstrap 5 either for the entire page or in a specific area? ...

Using JQuery to Send Form Data with an Ajax POST Request

On my web Node/Express app, I have implemented a basic messaging service and am currently attempting to submit the form using Ajax with the FormData object. While the form submission works perfectly without Ajax, all the req.body values are undefined when ...

Searching for a div table using XPATH in Python

Struggling to extract data from a table using Selenium in Python. Any suggestions on how to achieve this? https://i.stack.imgur.com/rPlKR.png <div class="js--property-table-body project-property-table__body"> <span aria-hidden=&quo ...