// count number of items
var count_items = $("#container .reviews-list").length;
// Keep a record of current page.
var current_page = 1;
// hide all items
$('#container .reviews-list').addClass('hide-reviews');
// display first 10 items
$.each($('#container .reviews-list'), function (index) {
if (index < 10 ) {
$(this).toggleClass('hide-reviews')
}
});
$(document).on('click tap', '#container .review-next', function () {
if ((current_page) * 10 >= count_items) {
return;
}
$('#container .reviews-list').addClass('hide-reviews');
for (var item = ((current_page) * 10 + 1); item < ((current_page + 1) * 10 + 1); item++) {
$("#container .reviews-list:nth-of-type(" + item + ")").removeClass('hide-reviews');
};
current_page += 1;
});
$(document).on('click tap', '#container .review-previous', function () {
if (current_page == 1) {
return;
}
$('#container .reviews-list').addClass('hide-reviews');
current_page -= 1;
for (var item = ((current_page - 1) * 10 + 1); item < ((current_page) * 10 + 1); item++) {
$("#container .reviews-list:nth-of-type(" + item + ")").removeClass('hide-reviews');
};
});
Pagination is a technique used to divide a large amount of data into smaller, more manageable chunks. It allows users to easily navigate through the data and improve the overall user experience. In this article, we will discuss how to implement pagination on a section of a webpage that displays reviews of a hotel using the jQuery library.
The first step in implementing pagination is to count the total number of items that need to be paginated. In this case, the code counts the total number of reviews and stores it in the variable “count_items”. The reviews are displayed in a container with the id "container " and each review is a child element with the class “reviews-list”.
The code then divides the total number of reviews by the number of items to be displayed per page.
To hide all the reviews, the code uses the jQuery method .addClass() and adds a class ‘hide-reviews’ (having display:none) to all the reviews. To display the first 10 reviews, the code uses the jQuery method .each() and toggles the class ‘hide-reviews’ to make them visible.
Next, the code sets up event listeners for the next and previous buttons with the class “review-next” and “review-previous” respectively. When the next button is clicked, the code removes the class ‘hide-reviews’ from the next 10 reviews and increments the current page variable by 1. When the previous button is clicked, the code removes the class ‘hide-reviews’ from the previous 10 reviews and decrements the current page variable by 1.
It also prevents the next button from functioning if the current page multiplied by 10 is greater than or equal to the total number of reviews, and prevents the previous button from functioning if the current page is equal to 1.