Infinite Scroll In JavaScript and Data from an API

25 August 2023
Infinite Scrolling
333
Views

In web development, making sure users stay interested and engaged is really important. There’s this cool trick that’s become quite popular – it’s like when you scroll through social media and new stuff just keeps loading automatically. In terms, think of it like a never-ending scroll at a wedding buffet, but with web content.

This trick uses a special tool called JavaScript, which is like a magician for websites. It’s a bit like how you might send a friend to get more food from the buffet while you keep eating – JavaScript fetches more content without you having to click anything. And the way it does this is pretty clever, like pretending to talk to a chef (we call it a Rest API) who keeps sending out new dishes as you ask.

Now, We’ll learn how this magic infinite scroll works, figure out how to use JavaScript to make it happen, and also get the hang of getting content from our pretend chef. So, get ready to make your website more fun and engaging with this endless scroll thing!

1. Introduction to Infinite Scroll Lists

Picture this: You’re scrolling through a webpage, like when you flick through your favorite social media app. Now, instead of clicking ‘Next Page’ to see more stuff, imagine if the content just kept flowing in as you scrolled down – that’s what we call ‘Infinite Scroll Lists.’

In easy words, it’s like a never-ending stream of content. No more waiting for the next page to load. It’s like having a magical infinite scroll that keeps unrolling itself with new things to see. Just like on social media, where fresh posts pop up automatically as you reach the bottom of the page. So, no more clicking around – it’s all right there as if the webpage knows exactly what you want to see!

2. JavaScript for Dynamic Content

JavaScript is like the superhero behind the scenes that makes infinite scroll lists happen. It’s got this amazing power to tinker with the web page’s insides, kind of like how you might rearrange your toys while playing.

In this way, we can update the page while you scroll down without clicking any button.

So, no more hunting for that “Next Page” button or tapping “Load More” over and over again. JavaScript does the heavy lifting, so you can just keep scrolling and the content keeps coming, like a never-ending story that you don’t want to put down!

3. Understanding Dummy APIs for Data

Alright, let’s talk about something called “Dummy APIs.” Imagine these as pretend waiters at a restaurant. Instead of bringing you real food, they give you fake dishes to practice with. In the world of web development, a Dummy API is like that – it gives you fake data to practice with, so you don’t have to deal with real server stuff just yet.

This comes in super handy when we’re building things like the never-ending scroll lists we just talked about. It’s like practicing your dance moves without the music playing – you can focus on getting the steps right without worrying about the actual performance. With Dummy APIs, we can work on making the scrolling smooth and perfect without getting tangled up in real data complications. It’s like a training ground for your web creations!

4. Step-by-Step Guide: Creating an Infinite Scroll List

Setting Up HTML Structure

First things first, we need to set up our web playground. Think of it like getting the stage ready for a play.

We’ll create a simple HTML structure. Imagine this structure as the frame of our webpage. Inside it, we’ll have a container that will hold all the stuff we want to scroll through – just like a basket holding all your favorite snacks.

This is the beginning of our web adventure. We’ve set the stage, and now we’re all set to bring in the magic of the infinite scroll

We’ve created a simple structure for our web page. The <ul> element with the ID “infinite-list” is where our infinite scroll list will come to life.

    <ul id='infinite-list'>
    </ul>

Styling with CSS

Having things neat and tidy is super important for a smooth ride on your website. Just like arranging your toys in a cool order, we’ll use CSS styles to make our never-ending scroll list look awesome and work like a charm. It’s like giving your webpage a snazzy outfit that not only looks good but also moves smoothly. So, get ready to make your webpage stylish and super user-friendly with some CSS magic!

        #infinite-list {
            /* We need to limit the height and show a scrollbar */
            width: 200px;
            height: 300px;
            overflow: auto;
            /* Optional, only to check that it works with margin/padding */
            margin: 30px;
            padding: 20px;
            border: 10px solid black;
        }

       /* Optional eye candy below: */
        #infinite-list li {
            padding: 10px;
            list-style-type: none;
        }
        #infinite-list li:hover {
            background: #ccc;
        }

Adding JavaScript Functionality

var listElm = document.querySelector('#infinite-list');
var batchSize = 10;
var currentOffset = 0;

listElm: This is like the big box where we’re going to put all the stuff for our never-ending scroll list. Imagine it as a container for all those cool things you want to show.

batchSize: Think of this as the number of goodies we grab each time we want more stuff to show up. So, if it’s set to 10, it’s like getting 10 candies every time you open a new bag.

currentOffset: This is like your bookmark that tells you where you left off in your favorite book. It assists the API in recalling what we’ve already presented and what’s going to happen next to display. As we scroll down and get more stuff, this bookmark changes so we know what to fetch next.

So, these three buddies team up to make sure your never-ending scroll list works like a charm. The container holds everything, the batch size decides how many things to bring at once, and the current offset keeps track of where we’re at. It’s like a dance party where everyone knows their moves!

Learn Load More Using JavaScript

Implementing the Fetch API

// Function to fetch items from the dummy API
var fetchItems = function(offset, limit) {
    var apiUrl = `https://dummyjson.com/posts?skip=${offset}&limit=${limit}`;

    return fetch(apiUrl)
        .then(response => response.json())
        .then(data => data.posts);
};

In this part, we’re defining a function called fetchItems. This function takes two parameters: offset and limit. These parameters will be used to construct the URL for fetching data from the dummy API.

Inside the function:

We create an apiUrl by using a template literal string that includes the offset and limit parameters. This URL points to the dummy API endpoint with the appropriate parameters.
We use the fetch API to make a GET request to the constructed apiUrl.
We handle the response by first converting it to JSON using .json(). Then, we extract the posts array from the returned data and return it as a promise.

// Function to load more items
var loadMore = function() {
    fetchItems(currentOffset, batchSize)
        .then(posts => {
            if (posts.length === 0) {
                return; // No more items to load
            }

            // Appending fetched items to the list
            posts.forEach(post => {
                var item = document.createElement('li');
                item.innerText = 'Post ' + post.id + ': ' + post.title;
                listElm.appendChild(item);
            });

            // Updating the offset for the next batch
            currentOffset += batchSize;
        })
        .catch(error => {
            console.error('Error fetching items:', error);
        });
};

Here, we define the loadMore function responsible for loading more items into the list when the user scrolls to the bottom.

Inside the function:

We call the fetchItems function with the current offset and batch size. This fetches the next batch of posts from the dummy API.
After fetching the posts, we check if the returned array is empty. If there are no more items to load, we simply return.
If there are items to load, we iterate through the posts array using the forEach loop. For each post, we create a new element, set its text content to include the post’s ID and title, and then append it to the listElm container.
We update the currentOffset by adding the batchSize, which ensures that the next batch of items will be fetched from the correct position.
Additionally, we use .catch to handle any errors that might occur during the API request and data processing.

Achieving Smooth Scroll

// Adding a scroll event listener
listElm.addEventListener('scroll', function() {
    if (listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) {
        loadMore(); // Load more items when scrolled to the bottom
    }
});

// Initial load of items
loadMore();

Now, let’s see how we make this magic happen when you scroll:

We’re putting on our detective hats and listening for a special event – when you scroll down in that container we talked about earlier. It’s like when you’re reading a scroll in an ancient story – we’re keeping an eye on where you are.

So, when you reach the very bottom, our superstar function, called “loadMore,” jumps into action. It’s like a helper who brings in more cool things to show you. This helper goes and gets more stuff, like fetching new chapters in a book, and adds them right where you were reading. This way, you don’t have to stop and wait – it’s like a smooth ride where the new stuff comes in seamlessly.

Imagine it like this: You’re reading a never-ending story, and as you finish one part, the next part magically appears right before your eyes. That’s what we’re doing with the scrolling – making sure you always have something exciting to see without any interruptions.

See the example on Codepen

Article Tags:
·
Article Categories:
JavaScript

Leave a Reply

Your email address will not be published. Required fields are marked *