The method by which content is presented and navigated plays an important role in web development. When it comes to displaying lists of items, such as articles, products, or images, two popular techniques used by developers are pagination and infinite scrolling. Each technique has its own set of advantages and challenges, making the choice between them a critical decision for web developers. In this article, we delve into the world of pagination and infinite scrolling, exploring their advantages, disadvantages, and the best use cases for each technique. We will also take a look at the major differences between both techniques, and this will help you decide which one to use in your next project.
What is pagination?
Pagination is a technique that involves dividing a large amount of content into smaller, separate pages, allowing users to navigate through the content sequentially through the use of page numbers or navigation controls. It is commonly used to improve the user experience, manage loading times, and organize information on websites.
Advantages of Pagination
1. Improved User Experience
Pagination provides an enhanced user experience. Instead of overwhelming users with an endless stream of content, pagination divides it into smaller, more digestible portions. This prevents information overload and makes it easier for users to find what they're looking for.
2. Faster Page Loading Times
Pagination can significantly improve page loading times, particularly when dealing with large files. By loading only a limited number of items on each page, websites reduce the amount of data transferred at once, resulting in quicker loading times.
3. Better Navigation Control
Pagination offers users greater control over their navigation. They can easily jump to the desired page or skip to the beginning or end of the content. This is particularly great when dealing with long lists or search results.
Disadvantages of Pagination
1. Disrupted User Flow
One of the main drawbacks of pagination is that it can disrupt the user's flow. Clicking through multiple pages to find the desired content can be frustrating and interrupt the overall user experience.
2. Potential for Higher Bounce Rates
Users may abandon a website if they have to click through multiple pages to find what they need. This can result in higher bounce rates, which can negatively impact SEO and overall user engagement.
3. Mobile Responsiveness Challenges
Pagination doesn’t work well on mobile devices. Limited screen space makes it harder to display page numbers or navigation controls, potentially leading to a less intuitive mobile experience.
Implementing Pagination Using HTML, CSS, and JS
Let's explore how to implement pagination using HTML, CSS, and JavaScript. We'll look at a simple example that demonstrates pagination for a list of items.
Create an HTML file
The first thing to do is set up your HTML file, like the one I created below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Pagination Example</title>
</head>
<body>
<div class="container">
<div class="content"></div>
<div class="nav"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Styling with CSS
You have to create a CSS file, which will contain the styling of the pagination project. This will help us create the required layout for the content, navigational elements, and images.
.content{
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.content > div{
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border: 2px solid black;
padding: 2rem;
margin: 1rem;
}
.content img{
max-width: 300px;
margin: 1rem;
}
.nav{
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.nav span{
font-size: 1.5rem;
border: lightgray solid 1px;
padding: 0.3rem;
margin: 0.3rem;
cursor: pointer;
}
Add functionality with JavaScript
You have to create a JS file (script.js), which must be linked to the HTML file.
// Define an array of items
const items= [
{
src: 'images/1.jpg',
desc: 'Asian children'
},
{
src: 'images/2.jpg',
desc: 'woman sitting'
},
{
src: 'images/3.jpg',
desc: 'man smiling'
},
{
src: 'images/4.jpg',
desc: 'man posing on street'
},
{
src: 'images/5.jpg',
desc: 'man reading book'
},
{
src: 'images/6.jpg',
desc: 'native american smiling'
},
{
src: 'images/7.jpg',
desc: 'a man thinking'
},
{
src: 'images/8.jpg',
desc: 'woman in the fields'
},
{
src: 'images/9.jpg',
desc: 'boy smiling'
},
{
src: 'images/10.jpg',
desc: 'model posing'
},
];
// Selecting elements and initializing variables
const nav= document.querySelector(".nav");
const content= document.querySelector(".content");
// Initialize variables for pagination
let pageIndex= 0;
let itemsPerPage= 3;
// Initial load of items
loadItems();
// Function to load items into content area
function loadItems() {
// Clear the content area
content.innerHTML= "";
// Loop through items based on the pageIndex and itemsPerPage
for (let i=pageIndex*itemsPerPage;
i<(pageIndex*itemsPerPage)+itemsPerPage; i++) {
if (!items[i]) {break}
// Create a new “div” element to display an item
const item= document.createElement('div');
item.innerHTML= `
<div>
<img src="${items[i].src}"/>
</div>
<div>
<span>${items[i].desc}</span>
</div>
`
// Append the item to the content area
content.append(item);
}
// Load navigational elements
loadNav();
}
// Function to load navigational elements
function loadNav() {
//clear the navigational area
nav.innerHTML= '';
// Loop through the pages based on number of items and itemsPerpage
for (let i=0; i<(items.length/itemsPerPage); i++) {
// Create a “span” element for each page
const span= document.createElement('span');
span.innerHTML= i+1; // Page number starts from 1
// Add a click event listener to each page element
span.addEventListener('click', (e) => {
pageIndex = e.target.innerHTML-1; // Set the new page index
loadItems(); // Reload items based on the new page
});
// Highlight the current page by increasing font size
if (i === pageIndex) {
span.style.fontSize = '2rem';
}
// Append the page element to the navigation area
nav.append(span);
}
};
Result:
In this code, an array named items was defined, which contained objects with image sources (src) and descriptions (desc) for each item. We selected two HTML elements with the classes "nav" and "content" and stored them in the variables nav and content, respectively. These elements were used for displaying the navigational elements and content.
Two variables, pageIndex and itemsPerPage, were initialized. pageIndex tracked the current page index, and itemsPerPage determined how many items were displayed per page.
The loadItems() function was called initially to fill the content area with some items. loadItems() then cleared the content area and then looped through items based on the pageIndex and itemsPerPage. For each item, it created a new <div> element using the createElement method and appended it to the content area.
After loading the items, the loadNav() function was called to create and display the navigation elements. loadNav() cleared the navigation area and then looped through the pages based on the total number of items and itemsPerPage. For each page, it created a span element with the page number and attached a click event listener to it.
Whenever a page was clicked, the event listener updated the pageIndex and called loadItems() to reload the items for the selected page.
Use Cases for Pagination
1. E-commerce Websites
E-commerce platforms often use pagination to display products. Users can browse through different pages of products, making it easier to find what they're looking for without overwhelming them with too many options at once.
2. Search Engine Results
Search engines like Google utilize pagination to display search results. Users can navigate through multiple pages of search results to find the most relevant information.
3. Blog Post Archives
Blogs frequently use pagination for archives. This allows readers to explore older blog posts without overwhelming them with a single long list.
4. Forums and Discussion Boards
Online forums and discussion boards use pagination to organize threads and posts. This keeps discussions manageable and helps users find relevant content within specific threads.
What is infinite scrolling?
Infinite scrolling is a loading technique where content is continuously loaded and displayed as a user scrolls down a webpage, eliminating the need for pagination or manual page navigation. It creates a seamless, uninterrupted user experience by dynamically fetching and adding additional content as the user scrolls.
Advantages of Infinite Scrolling
1. Seamless User Experience
Infinite scrolling offers a seamless user experience. Instead of clicking through pages, users can effortlessly scroll down to explore more content. This creates a fluid and engaging interaction, making it ideal for content-heavy websites and applications.
2. Higher User Engagement
Infinite scrolling can boost user engagement greatly. Since users don't need to make clicks to access more content, they are more likely to continue scrolling and exploring. This extended engagement can lead to increased time spent on your site, higher ad impressions, and improved conversion rates.
3. Ideal for Mobile Devices
Infinite scrolling is well-suited for mobile devices, where space is limited. It simplifies navigation and eliminates the need for users to click small page numbers or buttons, enhancing the mobile user experience.
Disadvantages of Infinite Scrolling
1. Difficulties in Finding Specific Information
While infinite scrolling is excellent for exploration, it can make it challenging for users to find specific information. When content keeps loading dynamically, users may struggle to locate a particular item or return to a previous section.
2. Performance Issues
Implementing infinite scrolling on websites with large files can lead to performance problems. Continuous content loading can slow down the page and consume significant bandwidth, potentially frustrating users with slower internet connections.
3. Footer Accessibility Issues
Footers on most websites usually include important links such as contact information, privacy policies, and terms of service. Infinite scrolling can make some links unreachable because visitors may never reach the bottom of the page.
Implementing Infinite Scrolling Using HTML, CSS, and JS
Let's delve into how to implement infinite scrolling using HTML, CSS, and JavaScript. We'll create a simple example that demonstrates infinite scrolling for a list of items retrieved from an API.
Create an HTML File
The first thing to do is set up your HTML file, like the one I created below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css"/>
<title>Document</title>
</head>
<body>
<div id="posts-container"></div>
<div class="loader">
<div class="circle"></div>
<div class="circle"></div>
<div class="circle"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Style with CSS
You have to create a CSS file, which will contain the styling of the infinite scroll project. This will help us create the required layout for the content and the loader.
body{
color: black;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
padding-bottom: 100px;
}
.post{
position: relative;
background: white;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
border-radius: 12px;
padding: 20px;
margin: 40px 0;
display: flex;
width: 40vw;
max-width: 800px;
}
.post .post-title{
margin: 0;
}
.post .post-body{
margin: 15px 0 0;
line-height: 1.3
}
.post .post-info{
margin-left: 20px;
}
.post .number{
position: absolute;
top: -10px;
right: -10px;
font-size: 15px;
width: 35px;
height: 35px;
border-radius: 50%;
color: white;
background: black;
display: flex;
align-items: center;
justify-content: center;
padding: 7px 10px;
}
.loader{
opacity: 0;
display: flex;
position: fixed;
bottom: 50px;
transition: opacity 0.3s ease-in;
}
.loader.show{
opacity: 1;
}
.circle{
background: black;
width: 10px;
height: 10px;
border-radius: 50%;
margin: 5px;
animation: bounce 0.5s ease-in infinite;
}
.circle:nth-of-type(2) {
animation-delay: 0.1s;
}
.circle:nth-of-type(3){
animation-delay: 0.2s;
}
@keyframes bounce {
0%,
100%{
transform: translateY(0);
}
50%{
transform: translateY(-10px)
}
}
Add functionality with JavaScript
You have to create a JS file (script.js), which must be linked to the HTML file.
// Selecting HTML elements and initializing variables
const postsContainer= document.getElementById("posts-container");
const loading= document.querySelector(".loader");
let limit= 30; // Set the initial limit for the number of posts to fetch
let page= 1; // Initializes the current page variable
// Async function to fetch posts from the API
async function getPosts(){
// Construct the URL for fetching posts with a specified limit and page
const res= await fetch( `https://jsonplaceholder.typicode.com/posts?_limit=${limit}&_page=${page}`
);
// Converts the fetched data to JSON format
const data= await res.json();
return data; // Returns the fetched data
}
// Async function to display fetched posts
async function showPosts(){
// Fetches posts using the getPosts function and store them in posts variable
const posts = await getPosts();
// Iterates through each post and create HTML elements to display them
posts.forEach(post => {
const postEl = document.createElement('div'); // Create a container for each post
postEl.classList.add('post'); // Adds the “post” class for styling
postEl.innerHTML= `
<div class="number">${post.id}</div> // Displays the post number
<div class="post-info">
<h2 class="post-title">${post.title}</h2> // Displays the post title
<p class="post-body">${post.body}</p> // Displays the post body
</div>
`;
postsContainer.appendChild(postEl); // Appends each post to the post container
})
};
// Function to show loading animation
function showLoading() {
loading.classList.add("show"); // Displays the loader animation by adding the “show” class
setTimeout(() => {
loading.classList.remove("show"); // Hides the loader animation after a delay
setTimeout(() => {
page++; // Increments the page variable to load the next page of posts
showPosts(); // Calls the showPosts() function to load and display new posts
}, 300); // Adds a delay before loading more posts
}, 1000); // Displays loader animation for 1 second before removing it
}
// Initial call to load and display the first set of posts
showPosts();
// Event listener for the “scroll” event on the window
window.addEventListener("scroll", () => {
const {scrollTop, scrollHeight, clientHeight} = document.documentElement;
// Checks if user has scrolled to bottom of the page
if (scrollTop + clientHeight >= scrollHeight - 5){
showLoading()
}
});
Result:
In this code, we selected two HTML elements and initialized them as variables, postsContainer and loader. The postsContainer variable represented where posts will be displayed. The loader variable represented the loader animation element. We also initialized two more variables, limit and page. The limit variable helped us to determine the number of posts to fetch at a time, while the page variable helped us to track the current page of posts.
The getPosts() function fetched posts from an external API. It constructed the URL with query parameters, _limit (number of posts per page) and _page (current page). The Fetch API was used to make the HTTP request, and await was used to wait for the response. The response data was converted to JSON using await res.json(). The function returned the fetched data.
The showPosts() function displayed the fetched posts. It called the getPosts function to retrieve posts and store them in the posts variable. Then, it iterated through each post in the posts array. For each post, it created a new <div> element with the class "post" to contain the post content. Inside the post element, it displayed the post number (ID), title, and body. The post element was appended to the postsContainer variable. Eventually, the showPosts function was called initially to load the first set of posts when the page loaded.
The showLoading function displayed and managed the loader animation. It added the "show" class to the loading element, making it visible. After a delay of 1000ms, it removed the "show" class, hiding the loader. It then incremented the page variable to load the next page of posts. Finally, it called showPosts to load and display the new posts.
An event listener was added to the window object to detect the "scroll" event. Whenever the user scrolled, the event listener checked if the user had scrolled to the bottom of the page. If the scroll position was within 5 pixels of the bottom of the page, it triggered the showLoading function. This created an infinite scroll effect, loading more posts as the user reached the end of the page.
Use Cases for Infinite Scrolling
1. Social Media Feeds
Social media platforms like Facebook, Twitter, and Instagram use infinite scrolling to present users with a continuous stream of posts, images, and updates. Users can keep scrolling to discover more content, creating an engaging and addictive user experience.
2. News Websites
News websites often employ infinite scrolling to present readers with a constant stream of news articles. Users can scroll down to explore a wide range of topics without the need to click through pages.
3. Image Galleries
Image galleries like Pinterest, which have large collections, make good use of infinite scrolling. Users can scroll through countless images effortlessly, discovering new content as they go.
4. Product Listings
E-commerce websites employ infinite scrolling to display products. This allows users to explore a vast catalog of items continuously, making it easier to discover products of interest.
Comparison between pagination vs infinite scrolling
Pagination and infinite scrolling are two different techniques for displaying content, each with its own set of advantages and disadvantages. Let's compare them in various areas to understand these differences better:
A. User Experience
Pagination: Pagination provides a structured and controlled user experience. By clicking on page numbers or navigation controls, users can easily go through the content. This is very useful when visitors need to discover specific information or the content is divided into sections.
Infinite Scrolling: It allows for a more fluid and continuous user experience. Users can scroll along the website without clicking, resulting in an engaging and seamless interaction. However, because it may require significant scrolling, it may be less ideal for people looking for specific information.
B. Loading Times:
Pagination: Due to the fact that only a limited amount of content is loaded at once, pagination often results in speedier loading times for individual pages. This is beneficial for websites with large files since it reduces initial page load times.
Infinite Scrolling: When dealing with large amounts of content, infinite scrolling might result in slower initial page load times. However, it distributes the loading of content over time, decreasing the need for consumers to wait for many pages to load.
C. Mobile-Friendliness:
Pagination: Pagination might be difficult on mobile devices with limited screen space. On touchscreens, small page numbers or navigation controls may be difficult to interact with.
Scrolling indefinitely: Scrolling indefinitely is often more mobile-friendly. It reduces the need for precise clicks on small buttons, allowing users to scroll through content on mobile devices more easily.
D. Content Visibility:
Pagination: Pagination can help users discover and access specific content. This is because the content is organized into discrete sections, and readers can navigate directly to a certain area or page.
Infinite Scrolling: Infinite scrolling can make it difficult to find content, especially if users are looking for anything specific. Users may have to scroll for a long time to find the information they seek, which can be frustrating.
E. Engagement:
Pagination: When content is well organized, pagination can make people visit different parts of a website. However, if customers do not quickly find what they are looking for, they may abandon the site.
Infinite scrolling encourages users to keep browsing and discovering new content, and this increases user engagement. This can lead to more site time and improved engagement metrics.
F. Accessibility:
Pagination: Pagination can make content more accessible by providing clear labels for different sections of content. Websites that use pagination are easier to navigate for users with disabilities.
Infinite Scrolling: Infinite scrolling can be difficult to navigate, especially if there is no obvious organization or no way to jump to certain sections. To ensure accessibility, careful design and implementation are required.
Conclusion
Pagination and infinite scrolling serve different purposes and are useful in different contexts. Pagination is great for organized and structured content, where users seek specific information or when faster loading times are critical. On the other hand, infinite scrolling provides a seamless and engaging user experience suitable for content exploration, mobile devices, and situations where user engagement is a priority. The choice between these techniques should be based on the specific goals and requirements of the website or application.