Tutorial on Creating a Web Loader using CSS and JavaScript

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Web loaders, also known as spinners, are visual elements used to indicate that a web page is loading content or processing an action. In this tutorial, we will learn how to create a custom web loader using CSS and JavaScript. The result will be an animated and visually appealing loader that you can incorporate into your web projects.

Prerequisites:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A code editor of your choice.

Step 1: HTML File Setup

We will start by creating a basic HTML file. Open your code editor and create an HTML file named “loader.html”. Add the following basic structure:

<!DOCTYPE html>
<html>
<head>
  <title>Web Loader Tutorial</title>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <div class="loader"></div>
  
  <script src="script.js"></script>
</body>
</html>

In this code, we have linked a CSS file named “styles.css” and a JavaScript file named “script.js” to the HTML file. Make sure to create these files in the same location as the HTML file.

Step 2: Styling the Loader with CSS

Open the “styles.css” file and add the following CSS code:

.loader {
  border: 16px solid #f3f3f3;
  border-top: 16px solid #3498db;
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 2s linear infinite;
  margin: 0 auto;
  margin-top: 200px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

In this code, we have created a div with the class “loader” that will act as our web loader. We have applied border styles, size, colors, and animation to the div to create a spinning effect. The “spin” animation will make the loader continuously rotate.

Step 3: Adding Functionality with JavaScript

Open the “script.js” file and add the following JavaScript code:

window.addEventListener('load', function() {
  var loader = document.querySelector('.loader');
  loader.style.display = 'none';
});

In this code, we have added a load event to the window object to ensure that the loader is hidden once the page and its content have been fully loaded. We use the querySelector function to select the element with the class “loader” and then modify its style to set the display property to “none”, hiding it.

Step 4: Displaying the Loader

Save all the files and open the “loader.html” file in your browser. You should see the web loader in action, continuously spinning. Once the page is fully loaded, the loader will automatically disappear due to the load event we added in JavaScript.

Congratulations! You have successfully created a custom web loader using CSS and JavaScript. You can now integrate this loader into your web projects to provide an visually appealing loading experience.

Leave a Comment