Creating a load more button with fade in effect in javascript

Updated: 20-Apr-2022 / Tags: Javascript Tutorials / Views: 1607 - Author: George

Introduction

What is a load more button?
We use a load more button in cases that we have a large amount of data to display, and we don't want to load them all at once. We give the user the option to click on the button (which is displayed after the loaded content) to view more content.

In this article we are going to see how to create such a mechanism.
Let me quick describe what we are going to do.
We are going to display books in our page which are stored in a JSON file. We are going to fetch the data from the JSON file, and we are going to store them in the browser's local storage, and from there, we are going to fetch them in groups and display them in the page when the user clicks on the load more button.

Click on the View Demo button to have a visual of what we are going to create.

The files structure

image of the projects folder in submlime text editor
  • In the project's root, we have a book-images/ folder where we have stored the books images.
  • We have a books.json file with the books data.
  • An index.html file where we are going to display the data.
  • A script.js file, where we are going to write the JavaScript code.
  • And a style.css file, with basic rules to make things a little prettier.

The JSON file

In the JSON file we have an array of objects. Every object is a book. And every book has properties. As you can see we have a title, an image, an about, a pages, and a year property. We are going to target those properties from the javascript file so we can display their values in the page.

[
	{
		"title": "JavaScript For Beginners",
		"image": "book-images/javascript.jpg",
		"about": "Learn JavaScript Programming with ease",
		"pages": 115,
		"year": "2017"
	},
	{
		"title": "HTML & CSS Crash Course",
		"image": "book-images/html-css.jpg",
		"about": "Learn html and css with easy to follow-step-by-step tutorials",
		"pages": 71,
		"year": "2015"
	},
	{
		"title": "Linux",
		"image": "book-images/linux.jpg",
		"about": "Command Line and Shell Scripting Bible",
		"pages": 818,
		"year": "2014"
	},
	{
		"title": "Java",
		"image": "book-images/java.jpg",
		"about": "Java Programming For Beginners",
		"pages": 221,
		"year": "2016"
	},
	{
		"title": "The Complete Guide to Blender Graphics",
		"image": "book-images/blender.jpg",
		"about": "Computer Modeling & Animation",
		"pages": 610,
		"year": "2016"
	},
	{
		"title": "How to Hack Computers",
		"image": "book-images/how-to-hack-computers.jpg",
		"about": "Hacking for beginners, penetration testing",
		"pages": 138,
		"year": "2015"
	},
	{
		"title": "PHP",
		"image": "book-images/php.jpg",
		"about": "Learn PHP in 24 Hours or Less",
		"pages": 119,
		"year": "2016"
	},
	{
		"title": "Mastering Machine Learning with Python in Six Steps",
		"image": "book-images/python.jpg",
		"about": "A Practical Implementation Guide to Predictive",
		"pages": 374,
		"year": "2017"
	},
	{
		"title": "Learn to Program with C",
		"image": "book-images/learn-C.jpg",
		"about": "Learn to Program using the Popular C Programming Language",
		"pages": 323,
		"year": "2015"
	}
]

The index file

In the index file and inside the body tags, we have a container with a class of "content" in line 2. This is where we are going to insert our books from the javascript file.

<body>
	<div class="content">
		<!-- content displayed from the javascript file -->

		<button onclick="loadData()" class="load-more-button"><span>❭</span> </button>
	</div>

	<script src="script.js"></script> <!-- Link to the javascript file -->
	<script>
		loadInitialItems();
	</script>
</body>
  • In line 5 we have the load more button. As you can see we have assigned an onclick event-listener, that means that every time a user clicks on the button the loadData() function will run.
  • In line 8 we have the link to the javascript file.
  • And in lines 9-11 we have another pair of script tags, and inside them we run a javascript function called loadInitialItems(). With this function we are going to display the first set of books in the page.

The javascript file

Lets build the javascript code piece by piece.
Let me say that will not explain in details the functions i use. This tutorial is rather a guide, on how we can implement a load more button in our page. Let's take for example the code below, i will not explain how the fetch() API works, instead i will say: We are using the fetch() method to fetch the data from the books.json file and store them in the browsers local storage in line 4.
And that is what we are doing first thing in the file.

fetch("books.json")
.then(response => response.json())
.then(books => {
	localStorage.setItem("books", JSON.stringify(books));
});

let container = document.querySelector(".content");
let loadMoreButton = document.querySelector(".content button");

let initialItems = 3;
let loadItems = 3;
  • In line 7 we are targeting the container element that we have in the html file so we can access it, and this is the element in where we are going to insert the data.
  • In line 8 we do the same thing with the load more button.
  • The container variable will give us access to the container element. and the loadMoreButton variable is holding the load more button. We will use those variables later on.
  • In line 10 we are setting the number of items (books), that we displaying when the page first loads. We are setting this value to three. That means we are going to see 3 book items on page load.
  • In line 11, we are setting the number of items that we want to load, when we click on the load more button.

Let's write our first function and that is the loadInitialItems(). This is the function that will run every time the page loads. The function is executed in the html file in line 10.

function loadInitialItems(){
	let books = JSON.parse(localStorage.getItem("books"));
	let out = "";
	let counter = 0;
	for(let book of books){
		if(counter < initialItems){
			out += `
				<div class="book">
					<div class="left">
						<img src="${book.image}" alt="">
					</div>
					<div class="right">
						<p class="title">${book.title}</p>
						<p class="about">${book.about}</p>
						<p class="info">Pages: ${book.pages} / Year: ${book.year} </p>
					</div>
				</div>
			`;
		}
		counter++;
	}

	let div = document.createElement("div");
	container.insertBefore(div, loadMoreButton);
	div.innerHTML = out;
}

Let's break the function down

  • In line 14 we fetch the data (books), from the local-storage and we store then in the books variable.
    function loadInitialItems(){
    	let books = JSON.parse(localStorage.getItem("books"));
    		
  • In line 15 we are initializing a variable named out to an empty string. We are going to use the out variable inside the for loop to store the books.
    	let out = "";
  • In line 16 we are creating a counter variable and set it's value to zero.
    	let counter = 0;
  • Next in line 17 we are going to have a for of loop. We are going to loop through the books variable, which is an array holding our books.
    	for(let book of books){
  • Inside the for of loop, and in line 18 we are going to have an if statement, with the following condition. If the counter variable is less than the initialItems (we set the initialItems to 3), then we are gonna add the current book in the out variable.
    		if(counter < initialItems){
  • In line 20 - 31 we have the html template that represents the book object. The whole template is added to the out variable.
    			out += `
    				<div class="book">
    					<div class="left">
    						<img src="${book.image}" alt="">
    					</div>
    					<div class="right">
    						<p class="title">${book.title}</p>
    						<p class="about">${book.about}</p>
    						<p class="info">Pages: ${book.pages} / Year: ${book.year} </p>
    					</div>
    				</div>
    			`;
    		
  • In line 32 we close the if statement.
    Next in line 33 we increment the counter by one.
    And in line 34 we close the for of loop.
    		} // close if statement
    		counter++;
    	} // close for of loop
    		
  • In line 35 - 37 we creating a div element to wrap the books, that the out variable holds , and then we are going to add the div tag containing the books, to the container in the html page.
    	let div = document.createElement("div");
    	container.insertBefore(div, loadMoreButton);
    	div.innerHTML = out;
    }
    		

The next function is the lodaData() function. The loadData() function will run every time we press the load more button.

function loadData(){
	let books = JSON.parse(localStorage.getItem("books"));
	let currentDisplayedItems = document.querySelectorAll(".book").length;

	let out = "";
	let counter = 0;
	for(let book of books){
		if(counter >= currentDisplayedItems && counter < loadItems + currentDisplayedItems){
			out += `
				<div class="book">
					<div class="left">
						<img src="${book.image}" alt="">
					</div>
					<div class="right">
						<p class="title">${book.title}</p>
						<p class="about">${book.about}</p>
						<p class="info">Pages: ${book.pages} / Year: ${book.year} </p>
					</div>
				</div>
			`;
		}
		counter++;
	}

	let div = document.createElement("div");
	container.insertBefore(div, loadMoreButton);
	div.innerHTML = out;
	div.style.opacity = 0;

	if(document.querySelectorAll(".book").length == books.length){
		loadMoreButton.style.display = "none";
	}

	fadeIn(div);
}

Function breakdown

  • In line 41 we fetch the data (books), from the local-storage.
    	let books = JSON.parse(localStorage.getItem("books"));
  • In line 42 we are counting the number of items that currently are displayed in the page. We need to know how many books are currently displayed so we skip them and fetch the next batch.
    	let currentDisplayedItems = document.querySelectorAll(".book").length;
  • In line 44 we initialize again the out variable, so we can store the data (books), as we did in the previous function.
    	let out = "";
  • In line 45 we have again a counter variable.
    	let counter = 0;
  • In line 46 we loop again through the books array.
    	for(let book of books){
  • In line 47 we have if statement that says:
    If the counter variable is greater or equal than the currentDisplayedItems (the books that are displayed on the page), and the counter is less than the loadItems plus> the currentDisplayedItems, only then we add the object (book) to the out variable.
    		if(counter >= currentDisplayedItems && counter < loadItems + currentDisplayedItems){

    Lets hard code this to make it more clearer.
    The counter variable starts at zero and in every iteration increments by one.
    So we have counter = 0.
    Lets say the currentDisplayedItems = 3.
    And we set the loadItems variable to 3 in line 11.

    if(counter(0) >= 3 && counter(0) < 3 + 3) // first iteration returns false.
    if(counter(1) >= 3 && counter(1) < 3 + 3) // second iteration returns false.
    if(counter(2) >= 3 && counter(2) < 3 + 3) // third iteration still false.
    if(counter(3) >= 3 && counter(3) < 3 + 3) // fourth iteration, returns true.
    if(counter(4) >= 3 && counter(4) < 3 + 3) // fifth iteration, returns true.
    if(counter(5) >= 3 && counter(5) < 3 + 3) // iteration number six, returns true.
    if(counter(6) >= 3 && counter(6) < 3 + 3) // iteration number seven, returns false.
    		
    You see that we don't add the first three objects in the out variable, because they are already displayed in the screen. We want only the objects in which the condition returns true.
    So we skip the books already displayed in the page and we grab the three next ones. Hope it makes sense.
  • In line 64 - 67 we creating a div element to wrap the books, that the out variable holds , and then we are going to add the div tag containing the books, to the container in the html page.
    And in line 67 we set the opacity to zero, because we are going to write a fadeIn() function to apply a fade-in effect to the new created element.
       let div = document.createElement("div");
    	container.insertBefore(div, loadMoreButton);
    	div.innerHTML = out;
    	div.style.opacity = 0;
    		
  • Next we are checking with an if statement if there are any objects (books) left to display. If not, we hide the load more button.
        if(document.querySelectorAll(".book").length == books.length){
    		loadMoreButton.style.display = "none";
    	}
    		
  • In line 73 we call a function called fadeIn() which we will write next, and we pass in as an argument the newly created div element.
    	fadeIn(div);
    } // end of function.
    		

Let's write our last function which is the fadeIn() function. The logic here is simple. We set a variable named opacity, to zero. We know that we set the opacity to the div element, that we created in the previous function to zero. So the opacity = 0 statement is our starting point.

Next we use a setInterval() function and we execute an if statement until the opacity reaches a value of one opacity = 1. Every time the if statement is executed we increase the opacity by a value of 0.1.

And when the if statement is done, inside the else clause we stop the setInerval() with the clearInterval() function.

function fadeIn(div){
	let opacity = 0;
	let interval = setInterval(function(){
		if (opacity <= 1) {
			opacity = opacity + 0.1; // increasing the opacity by 0.1.
			div.style.opacity = opacity; // making the div element gradual visible.
		}else{
			clearInterval(interval);
		}
	}, 30);
}

Summary

And that's it, we have successfully created a load more button with a fade-in effect. If you clicked on the view demo button and saw the demo, this is exactly the code that is executed.

Source code

You can download the source code and use it in any way you like.

Times downloaded: 245

Buy me a coffee

If you like to say thanks, you can buy me a coffee.

Buy me a coffee with paypal

Comment section

You can leave a comment, it will help me a lot.

Or you can just say hi. 😉