Simple pagination in javascript
I'll address any questions you have... but here is an improved pattern you should follow to reduce code duplication.
As a sidenote though, you should consider not doing pagination on client-side. Since if you have a huge dataset, it would mean you need to download all the data before your page loads. Better to implement server-side pagination instead.
Fiddle: http://jsfiddle.net/Lzp0dw83/
HTML
<div id="listingTable"></div>
<a href="javascript:prevPage()" id="btn_prev">Prev</a>
<a href="javascript:nextPage()" id="btn_next">Next</a>
page: <span id="page"></span>
Javascript (put anywhere):
var current_page = 1;
var records_per_page = 2;
var objJson = [
{ adName: "AdName 1"},
{ adName: "AdName 2"},
{ adName: "AdName 3"},
{ adName: "AdName 4"},
{ adName: "AdName 5"},
{ adName: "AdName 6"},
{ adName: "AdName 7"},
{ adName: "AdName 8"},
{ adName: "AdName 9"},
{ adName: "AdName 10"}
]; // Can be obtained from another source, such as your objJson variable
function prevPage()
{
if (current_page > 1) {
current_page--;
changePage(current_page);
}
}
function nextPage()
{
if (current_page < numPages()) {
current_page++;
changePage(current_page);
}
}
function changePage(page)
{
var btn_next = document.getElementById("btn_next");
var btn_prev = document.getElementById("btn_prev");
var listing_table = document.getElementById("listingTable");
var page_span = document.getElementById("page");
// Validate page
if (page < 1) page = 1;
if (page > numPages()) page = numPages();
listing_table.innerHTML = "";
for (var i = (page-1) * records_per_page; i < (page * records_per_page); i++) {
listing_table.innerHTML += objJson[i].adName + "<br>";
}
page_span.innerHTML = page;
if (page == 1) {
btn_prev.style.visibility = "hidden";
} else {
btn_prev.style.visibility = "visible";
}
if (page == numPages()) {
btn_next.style.visibility = "hidden";
} else {
btn_next.style.visibility = "visible";
}
}
function numPages()
{
return Math.ceil(objJson.length / records_per_page);
}
window.onload = function() {
changePage(1);
};
UPDATE 2014/08/27
There is a bug above, where the for loop errors out when a particular page (the last page usually) does not contain records_per_page
number of records, as it tries to access a non-existent index.
The fix is simple enough, by adding an extra checking condition into the for loop to account for the size of objJson
:
Updated fiddle: http://jsfiddle.net/Lzp0dw83/1/
for (var i = (page-1) * records_per_page; i < (page * records_per_page) && i < objJson.length; i++)
Simple pagination with jquery or javascript
Using jQuery:
<a href="#" id="prev">Prev page</a>
<a href="#" id="next">Next page</a>
<div class="pagination">
<div class="post" id="page1"> <!-- I gave every "page" an ID. -->
<h3> head1 </h3>
<p> Test1 </p>
</div>
<div class="post" id="page2">
<h3> head2 </h3>
<p> Test2 </p>
</div>
<div class="post" id="page3">
<h3> head3 </h3>
<p> Test3 </p>
</div>
<div class="post" id="page4">
<h3> head4 </h3>
<p> Test4 </p>
</div>
<div class="post" id="page5">
<h3> head5 </h3>
<p> Test5 </p>
</div>
<div class="post" id="page6">
<h3> head6 </h3>
<p> Test6 </p>
</div>
</div>
All you need to do in this situation is dynamically hide every page except the one you want to see:
function showPage(page) {
$('.pagination .post:not(#page'+page+')').hide();
$('.pagination .post#page'+page).show();
}
If you want next and previous buttons you can easily do so like this:
function prevPage() {
if (page == 1) {
page = $('.pagination .post').length;
} else {
page--;
}
showPage(page);
}
function nextPage() {
if (page == $('.pagination .post').length) {
page = 1;
} else {
page++;
}
showPage(page);
}
Just note that you need to store the number of the page (I used page
in the example) if you want to have next and previous buttons.
Example Fiddle
Simple pagination algorithm with range
For a non dynamic approach, you could separate the resilt into three parts, where the different actual page creates different array.
function getPagination(page, total) {
if (page < 3) return [1, 2, 3, '...', total];
if (page < total - 2) return ['...', page - 1, page, '...', total];
return [1, '...', total - 2, total - 1, total];
}
for (let i = 1; i <= 10; i++) console.log(i, ':', ...getPagination(i, 10));
.as-console-wrapper { max-height: 100% !important; top: 0; }
jQuery simple pagination
Please see if it help for you. here is your javascript
$(document).ready(function(){
$("#item1").addClass("active");
$(".prev").click(function(){
// do previous tab
var $el = $(".active").prev(".itemWrap");
if($el.length){
$(".itemWrap").each(function() {
$(this).removeClass("active");
});
$el.addClass("active");
}
});
$(".next").click(function(){
// do next tab
var $el = $(".active").next(".itemWrap");
if($el.length){
$(".itemWrap").each(function() {
$(this).removeClass("active");
});
$el.addClass("active");
}
});
});
and here is your css
.itemWrap
{
display:none;
}
.itemWrap.active
{
display:block;
}
here is the fiddle
Paginate Javascript array
You can use Array.prototype.slice
and just supply the params for (start, end)
.
function paginate(array, page_size, page_number) { // human-readable page numbers usually start with 1, so we reduce 1 in the first argument return array.slice((page_number - 1) * page_size, page_number * page_size);}
console.log(paginate([1, 2, 3, 4, 5, 6], 2, 2));console.log(paginate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], 4, 1));
Js pagination page links don't work
$('.pagination ul').on('click', 'a', function(e){
e.preventDefault();
const pgNum = parseInt($(e.target).text());
showPage(studentList, pgNum);
$(this).parent().siblings().children().removeClass('active');
$(this).addClass('active');
});
The problem is with the above function(showPage(studentList, pgNum);). While you click on the pagination links the whole student array is being passed as the studentList. Instead you might want to send only the result that you get after your search query has given you a new studentArray.
below is the js that i have made some changes to, might get you the result you want.
// Setting up variables
const $studentList = $('.student-list').children();
var $changedStudentList = $studentList;
$('.student-list').prepend('<div class="notFound"></div>');
$('.notFound').html(`<span>No results</span>`);
$('.notFound').hide();
// Bulding a list of ten students and displaying them on the page
function showPage(studentList, pageNum = 1){
const showPerPage = 10;
// hide all students on the page
$(studentList).hide();
// Get start/end for each student based on the page number
const calcStart = (pageNum) => pageNum === 1 ? 0 : (pageNum - 1) * showPerPage;
const start = calcStart(pageNum);
const end = pageNum * showPerPage;
// Looping through all students in studentList
$(studentList).slice(start,end).each(function(i, li){
// if student should be on this page number
// show the student
$(li).fadeIn(50);
});
}
// Search component
const searchBar = `
<div class="student-search">
<input placeholder="Search for students...">
<button>Search</button>
</div>
`;
$('.page-header').append(searchBar);
$('.student-search input').on('keyup', function(){
const searchQuery = $(this).val();
const searchResults = searchStudent($('.student-list li'), searchQuery.toUpperCase());
$changedStudentList = searchResults;
showPage(searchResults);
appendPageLinks(searchResults);
});
// Student search
function searchStudent(element, filter){
$(element).each(function(){
if($(this).text().toUpperCase().includes(filter)){
$(this).show();
} else {
$(this).hide();
}
});
let num = $('.student-item:not([style*="display: none"])').length;
let searchRes = $('.student-item:not([style*="display: none"])');
num > 0 ? $('.notFound').hide() : $('.notFound').show();
return searchRes;
};
// Creating all page links based on a list of students
function appendPageLinks(studentList){
// determine how many pages for this student list
totalPageNum = Math.ceil(studentList.length / 10);
// create a page link section
const pagination = 'pagination';
// add a page link to the page link section
// if class the element already exists
if($('.pagination').length === 0){
$('.page').append(`
<div class="${pagination}">
<ul></ul>
</div>
`);
}
// remove the old page link section from the site
$('.pagination ul').children().remove();
if (totalPageNum > 1){
// 'for' every page
for(let i=0; i<totalPageNum; i++){
const pageLink = `
<li>
<a href="#">${i + 1}</a>
</li>
`;
// append our new page link section to the site
$('.pagination ul').append(pageLink);
}
}
$('.pagination ul li').children().first().addClass('active');
// define what happens when you click a link (event listener)
$('.pagination ul').on('click', 'a', function(e){
e.preventDefault();
const pgNum = parseInt($(e.target).text());
// Use showPage() to display the page for the link clicked
showPage($changedStudentList, pgNum);
// mark that link as 'active'
$(this).parent().siblings().children().removeClass('active');
$(this).addClass('active');
});
}
showPage($studentList);
appendPageLinks($studentList);
Related Topics
Javascript Submit Multiple Forms With One Button
Write a Auto-Fill and Submit Web Form Program
How to Close Sweet Alert on Ajax Request Completion
Trying to Add Image to Pdf Using Jspdf
Filtering Item from Nested Object Array in Typescript
How to Set Page Size and Set Margin in Print in Internet Explorer With JavaScript and CSS
Webcam Js Error in Chrome: Could Not Access Webcam
Disable Click Outside of Bootstrap Modal Area to Close Modal
Jquery - Ajax Returning Error 500 on Some Posts
How to Instantiate a JavaScript Class in Another Js File
How to Get 30 Days Prior to Current Date
How to Prevent a Key Input from Appearing in Input Field
How to Determine Server Disconnection from Signalr Client
Disable Pdf Download and Save Option
Adding Whitespace to a String in Typescript (In Angular)
How to Detect If Two Divs Are Touching/ Collision Detection
Detect If Html5 Video Element Is Playing
Jest Encountered an Unexpected Token: Syntaxerror: Unexpected Token {