Congratulations for completing this resource! Mark it as completed to track your progress.
If you've ever stumbled upon a website called http://endless.horse/ you're likely familiar with the concept of infinite scroll.
Upon landing on the site, you'll be greeted with a horse. However, when you scroll down to see the horse's feet, you'll find that the legs just keep getting longer and longer!
Seems a bit silly, right? 🤪
Well, this is a great example of ‘infinite scroll’ - and you may be surprised to know that it's a popular feature in web development!
You just need to look at social media sites like Twitter and Pinterest to see infinite scroll in action!
As you scroll down the page, more posts will load - eliminating the need for multiple pages.
Let’s learn more about it.
Here are some of the benefits of infinite scroll:
Infinite scroll can result in users spending more time on your site, reducing bounce rates. They don’t have to click a button to view more posts - or navigate to multiple pages!
They also don’t have to push a button to go back - they can just scroll up.
This can contribute to higher rankings, more conversions - and ultimately, happier users.
Take, for example, chat applications like Slack - infinite scroll can result in a continuous flow of communication between users.
Infinite Scroll allows users to more easily discover new content. Data loaded dynamically is more accessible and discoverable.
Infinite scroll provides a modern way for websites with substantial content to display it without overwhelming the user.
If you’re wondering how you can implement this in your own website or software, follow this step-by-step guide to get it up and running in no time!
Decide which element the infinite scroll feature is going to be applied to.
Perhaps it’s going to be a list of names, some images, user profiles, etc.
For this example, we are going to use some random fox images that we’ll get from a free API.
So, our website will look something like this when we're done:
As you scroll, you'll notice that more and more fox images will load! You won't be able to reach the bottom of the page. This is infinite scroll in action! 🔥
Setting Up the Basic HTML Structure
Once you’ve decided which elements your infinite scroll feature will be applied to, you can then create the basic HTML document and HTML structure.
Make sure that your HTML has a container for the content that will be loaded infinitely.
Our file will look something like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h1 class="header">Fox Images</h1>
<div class="container">
<!-- Images of foxes will appear here -->
</div>
</body>
</html>
Create your CSS stylesheet
Once you’ve created the HTML structure, style the elements with your desired CSS.
For this example, we’re going to keep the stylesheet simple.
.container {
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
}
.header {
font-size: 32px;
color: black;
text-align: center;
font-family: Verdana, sans-serif;
}
img {
width: 400px;
height: 400px;
margin: 4px;
object-fit: cover;
}
Don't forget to connect your CSS stylesheet to your index.html file! 🚀
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<! –– Add your stylesheet ––>
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 class="header">Fox Images</h1>
<div class="container">
<!-- Images of foxes will appear here -->
</div>
</body>
</html>
Add your JavaScript
Create a JavaScript file and connect it to your HTML file using the script tag.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<! –– Add your stylesheet ––>
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 class="header">Fox Images</h1>
<div class="container">
<!-- Images of foxes will appear here -->
</div>
<! –– Add your JavaScript file ––>
<script src="src/script.js"></script>
</body>
</html>
Now we can start writing our JavaScript! 🎉
First, select the container where we’ll be showing our images:
const container = document.querySelector(".container");
Grab the URL of the API:
const URL = `https://randomfox.ca/images/`;
Now, the way that this API works is that you can fetch a random fox image by changing the number at the end of the URL.
For example:
"https://randomfox.ca/images/48.jpg"So let’s make a function to load the images:
function loadImages(numImages = 6) {
let i = 0;
while (i < numImages) {
const img = document.createElement("img");
img.src = `${URL}${getRandomNumber()}.jpg`;
container.appendChild(img);
i++;
}
}
loadImages();
In the above function, we are using a while loop to create a new image element and append it to our empty container. Let’s use 6 images to start with
You might notice that we are using a function to generate a random number to fetch a random fox image. But where is this function? Let’s make one:
function getRandomNumber() {
return Math.floor(Math.random() * 100);
}
In the above function, we are generating a random decimal number between 0 and 1 with Math.random() - such as 0.5647.
But we are looking for a number that is say between 0 and 100.
So we can multiply this number by 100.
In this example, we would get 56.47.
But as we need a whole number (an integer), we can use Math.floor() which rounds the number down to the nearest whole number.
So the number would become 56.
At this stage, you should see six foxes appear on your page!
Infinite scroll
For the final step, we’ll be adding the infinite scroll!
To do this, we’ll need to make the following function:
window.addEventListener("scroll", () => {
if (
window.scrollY + window.innerHeight >=
document.documentElement.scrollHeight
) {
loadImages();
}
});
In a nutshell, this function is saying that:
If the sum of and is greater than or equal to the it means that we have reached the end of the document and thus we need to load more images!
If you take a look at your website now, you should see that you are unable to scroll to the bottom of the page.
More and more images of foxes will load as you scroll! 🦊
Congratulations! You have now implemented ‘infinite scroll’!
As an added bonus, consider adding a loading spinner as well. This will show the user that more content is being loaded each time.
This helps to reduce frustration and manage user expectations.
While the user is scrolling down the page, you don’t want to be fetching a ton of data to display as this will cause delays in loading the new content which will create a negative user experience.
You should ensure that your code is optimized to handle the incremental loading of your content.
While infinite scroll can enhance user experience in web development by removing the need to click to view more content, it can also create accessibility issues for users who have limited bandwidth or who use screen readers.
You may want to consider a way for users to disable infinite scrolling if needed.
SEO refers to Search Engine Optimization. If your website has good SEO, it is likely to receive more traffic and visits from your ideal client.
Unfortunately though, search engine crawlers may not index content that is loaded dynamically through infinite scroll, so it is crucial to make sure that all content is accessible and crawlable to maintain visibility in search engine results.
If you’ve implemented infinite scroll - your users may never get to see the footer of your website which may contain important information! Keep this in mind.
To overcome some of these drawbacks, you can also consider these 2 options:
Use infinite scroll with a load more button
While this may seem to defeat the purpose because it requires users to click on the button, it offers several advantages - such as allowing users to have control over the amount of content that is loaded if they have limited data; and they can access the footer of your site.
Use infinite scroll in combination with pagination
When users reach the end of the initial content, they are offered a pagination bar to go to the next page. This can be seen on the Google shopping page, for example.
It offers the advantage of allowing users to go back and look at specific items on specific pages.
If you'd like to learn how to implement infinite scroll in some real projects, head over to our YouTube channel:
Build Modern Next 14 Server Side App with Server Actions, Infinite Scroll & Framer Motion AnimationsInfinite scrolling is a powerful tool that can provide a smooth, uninterrupted browsing flow!
However, it's important to consider its implications on aspects like data loading and SEO.
Always consider your audience and the content of your site when deciding whether to implement infinite scrolling in your web development process.
With careful planning and thoughtful design, infinite scrolling can be an effective way to modernize your website and keep users engaged! 🔥