Loading indicators
Part of the JavaScript in Action section of Coddy's HTML journey. Lesson 10 of 27.
Loading indicators are small visual elements (like spinners or animations) that let users know something is happening in the background (when submitting a form or loading data). They improve user experience by showing feedback instead of leaving the user guessing.
First, add this HTML to your page:
<button id="loadBtn">Load Data</button>
<div id="loading-spinner" class="spinner-hidden">
<div class="spinner"></div>
</div>Then, add CSS to style the element so it looks like a wheel, and use keyframes to keep spinning it endlessly. We also use a .hidden class to keep the spinner invisible when needed.
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.hidden {
display: none;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}Now, add JavaScript to show/hide the spinner:
const loadBtn = document.getElementById("loadBtn");
const spinner = document.getElementById("spinner");
loadBtn.addEventListener("click", function () {
// Show spinner
spinner.classList.remove("hidden");
// After 3 seconds, hide spinner and show alert
setTimeout(function () {
spinner.classList.add("hidden");
alert("Data loaded successfully!");
}, 3000);
});When the button is clicked, we show the spinner, wait 3 seconds, then hide it and display an alert.
Challenge
EasyYour task:
- Inside the button's click event listener, add code to show the spinner by removing the "hidden" class. Place this code before the setTimeout function.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Loading Spinner Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>Welcome to My Page</h1>
<p>Click the button below to simulate loading data.</p>
<button id="loadBtn">Load Data</button>
<div id="spinner" class="spinner hidden"></div>
</div>
<script src="script.js"></script>
</body>
</html>
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in JavaScript in Action
Practice on your own: Web playground