< BACK TO COMPONENTS

Create a Love Loader using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn to build a captivating Love Loader using HTML, CSS, and JavaScript. Elevate user engagement with this step-by-step tutorial.


Create a Love Loader using HTML, CSS, and JavaScript.jpg

In the vast landscape of web development, creating a compelling user experience is paramount. One way to captivate your audience and infuse your website with a dash of charisma is by incorporating love-themed loaders. These delightful animations not only serve a functional purpose by signaling content loading but also evoke positive emotions, leaving a lasting impression on your visitors. In this comprehensive tutorial, we will embark on a journey to craft a Love Loader, using the dynamic trio of HTML, CSS, and JavaScript.


Why a Love Loader, you ask? Because love is a universal language, and what better way to connect with your users than through a symbol of affection? Whether you're building a personal blog, an e-commerce site, or a creative portfolio, a Love Loader can be the secret ingredient that transforms a mundane loading screen into a memorable moment. With a bit of coding magic and creativity, you'll not only elevate the aesthetics of your website but also foster a sense of engagement that keeps users eagerly awaiting what's to come.


This tutorial will walk you through each step of the process, from setting up the HTML structure to infusing it with style using CSS and adding interactivity with JavaScript. We'll explore how to integrate love-themed graphics, ensuring your Love Loader resonates with your website's theme and message. So, without further ado, let's dive into the world of Love Loaders and create something truly enchanting!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our loader.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


Let me explain each part of it:


1. <!DOCTYPE html>: This is the document type declaration, indicating that the document is an HTML5 document.


2. <html lang="en">: This is the opening tag for the HTML document. The lang attribute is set to "en," indicating that the document is written in English.


3. <head>: This section contains metadata about the web page, which is not visible to users but is important for search engines and browsers.


  • <title>Love Loader</title>: This line sets the title of the web page to "Love Loader." The title is displayed in the browser's title bar or tab.
  • <meta charset="UTF-8" />: This meta tag specifies the character encoding of the document, which is set to UTF-8, a character encoding that supports a wide range of characters and symbols.
  • <meta name="viewport" content="width=device-width" />: This meta tag is used to control the viewport settings of the web page, ensuring that the page adapts to different screen sizes on mobile devices.
  • <link href='https://fonts.googleapis.com/css?family=Ubuntu:400,300' rel='stylesheet' type='text/css'>: This line links to an external stylesheet hosted on Google Fonts. It imports the "Ubuntu" font with two different weights (400 and 300) to be used in the web page.
  • <link rel="stylesheet" href="styles.css" />: This line links to an external CSS (Cascading Style Sheets) file named "styles.css" to apply styles to the HTML elements on the page.

4. <body>: This section contains the visible content of the web page that users will see in their browsers.


5. <div class="loader">: This is a <div> element with a class attribute set to "loader." It's used to group and style the content within it.


  • <canvas width="480px" height="480px" id="loader"></canvas>: Inside the "loader" div, there's an HTML5 <canvas> element with a width and height of 480 pixels. It also has an id attribute set to "loader." The canvas element is typically used for drawing graphics and animations.
  • <h1>Loading</h1>: This is an <h1> (header) element that displays the text "Loading." It's a heading for the content within the "loader" div.

6. <script src="script.js"></script>: This line includes an external JavaScript file named "script.js." JavaScript is a programming language used for adding interactivity and functionality to web pages. The script in "script.js" will be executed by the browser.


This is the basic structure of our love loader using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the loader is in place, the next step is to add styling to the loader using CSS.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our loader. Let me explain each part of the code:


1. html,body: This selector targets both the html and body elements in your HTML document.


  • padding: 0; and margin: 0;: These lines remove any default padding and margin applied to the html and body elements. This ensures that there is no extra space around the edges of the page.
  • overflow: none;: This line specifies that neither the html nor the body should have scrollbars if the content exceeds the viewport dimensions (width and height).
  • width: 100%; and height: 100%;: These lines set the width and height of both the html and body elements to occupy the entire viewport. In other words, it makes sure that the webpage takes up the full available space in the browser window.

2. body: This selector specifically targets the body element.


  • background: url('https://i.imgur.com/UMnw0tW.jpg');: This line sets the background image of the body. It uses the specified URL ('https://i.imgur.com/UMnw0tW.jpg') as the background image.
  • font-family: 'Ubuntu', sans-serif;: This line sets the font family for the text content inside the body element. It will use the 'Ubuntu' font if available, and if not, it will fall back to a generic sans-serif font.
  • background-position: center center;: This line centers the background image both horizontally and vertically within the body.
  • background-size: cover;: This line ensures that the background image covers the entire body element, scaling it as needed to fill the available space while maintaining its aspect ratio.
  • color: #121212;: This sets the text color inside the body to a dark gray (#121212).

3. .loader: This is a class selector targeting elements with the class "loader."


  • position: absolute;: This positions elements with the "loader" class absolutely within their closest positioned ancestor. In this case, they are positioned relative to the body.
  • top: 50%;: It positions the top of the loader element at 50% of the height of its parent container (in this case, the body).
  • margin: -240px;: It negatively margin the loader element by 240 pixels in all directions, effectively centering it both horizontally and vertically within its parent container.
  • left: 50%;: It positions the left edge of the loader element at 50% of the width of its parent container.
  • width: 480px; and height: 480px;: These lines set the dimensions (width and height) of the loader element to be 480 pixels each.

4. .loader h1: This selector targets the h1 elements inside elements with the class "loader."


  • position: absolute;: This positions the h1 elements absolutely within their closest positioned ancestor, which is the element with the "loader" class.
  • top: 0px; and left: 0px;: These lines position the h1 elements at the top-left corner of their parent element (the "loader" element).
  • text-align: center;: It centers the text inside the h1 elements horizontally.
  • width: 100%;: It makes the h1 elements take up the full width of their parent container.
  • line-height: 420px;: This line sets the line height (vertical spacing between lines of text) to 420 pixels.
  • font-size: 24px;: It sets the font size of the text within the h1 elements to 24 pixels.
  • color: rgba(0, 0, 0, 0.24);: This sets the text color to a semi-transparent black color, giving it a subtle grayish appearance.

This will give our love loader an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

html,body{
  padding:0;
  margin:0;
  overflow:none;
  width:100%;
  height:100%;
}

body {
  background:url('https://i.imgur.com/UMnw0tW.jpg');
  font-family: 'Ubuntu', sans-serif;
  background-position:center center;
  background-size:cover;
  color: #121212;
}
.loader{
  position:absolute;
  top:50%;
  margin:-240px;
  left:50%;
  width:480px;
  height:480px;    
}
.loader h1{
  position: absolute;
  top:0px;
  left:0px;
  text-align: center;
  width:100%;
  line-height:420px;
  font-size:24px;
  color:rgba(0,0,0,0.24);
  font-weight:100;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript. The loader displays animated particles forming a heart shape. Let's break down the code step by step:


Loadr is defined as an anonymous function that takes an id as a parameter, presumably the ID of an HTML canvas element where the loader animation will be rendered.


Several constants are defined for configuration:


  • max_size: The maximum size of individual particles.
  • max_particles: The maximum number of particles in the animation.
  • min_vel: The minimum velocity of particles.
  • max_generation_per_frame: The maximum number of new particles generated in each animation frame.

Various variables are initialized, including references to the canvas element, its context, canvas dimensions, animation flags, an array to store particle objects, and time-related variables.


isInsideHeart(x, y) is a function that checks whether a point (x, y) is inside the heart shape. It uses a mathematical equation to determine this.


random(size, freq) is a function that generates a random number using a frequency distribution. It starts with size and iteratively divides it by a frequency until it reaches a value less than 1. The sum of these generated values is returned as the random number.


The Particle constructor function is defined to create individual particle objects. Each particle has properties like position, size, velocity, and color. The draw method is used to draw the particle on the canvas, and the move method updates the particle's position based on its velocity.


movementTick is a function responsible for generating new particles and updating the positions of existing particles. It calculates the time delta (dt) and calls the move method on each particle.


The tick function is the animation loop. It clears the canvas, draws each particle, and requests the next animation frame.


The start and done methods are defined, but they are empty and not used in the provided code.


Finally, a setInterval is used to repeatedly call the movementTick function at approximately 60 frames per second (16ms interval), and the tick function is called to start the animation loop.


Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.


Loadr = new (function Loadr(id){
  // # Defines
  const max_size = 24;
  const max_particles = 1500;
  const min_vel = 20;
  const max_generation_per_frame = 10;

  // #Variables
// sometimes i wrote code horrible enouhg to make eyes bleed 
  var canvas = document.getElementById(id);
  var ctx = canvas.getContext('2d');
  var height = canvas.height;
  var center_y = height/2;
  var width = canvas.width;
  var center_x = width / 2;
  var animate = true;
  var particles = [];
  var last = Date.now(),now = 0;
  var died = 0,len = 0,dt;

  function isInsideHeart(x,y){
      x = ((x - center_x) / (center_x)) * 3;
      y = ((y - center_y) / (center_y)) * -3;
      // Simplest Equation of lurve
      var x2 = x * x;
    var y2 = y * y;
    // Simplest Equation of lurve
  
return (Math.pow((x2 + y2 - 1), 3) - (x2 * (y2 * y)) < 0);
  
}
  
function random(size,freq){
      var val = 0;
      var iter = freq;
      
do{
          size /= iter;
          iter += freq;
          val += size * Math.random();
      }while( size >= 1);
      
return val;
  }

  function Particle(){
      var x = center_x;
      var y = center_y;
      var size = ~~random(max_size,2.4);
      var x_vel = ((max_size + min_vel) - size)/2 - (Math.random() * ((max_size + min_vel) - size));
      var y_vel = ((max_size + min_vel) - size)/2 - (Math.random() * ((max_size + min_vel) - size));
      var nx = x;
var ny = y;
var r,g,b,a = 0.05 * size;

this.draw = function(){
  r = ~~( 255 * ( x / width));
  g = ~~( 255 * (1 - ( y / height)));
  b = ~~( 255 - r );
  ctx.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  ctx.beginPath();
  ctx.arc(x,y,size,0, Math.PI*2, true); 
  ctx.closePath();
  ctx.fill();
}

      this.move = function(dt){

  nx += x_vel * dt;
  ny += y_vel * dt;
  if( !isInsideHeart(nx,ny)){
    if( !isInsideHeart(nx,y)){
      x_vel *= -1;
      return;
    }
            
    if( !isInsideHeart(x,ny)){
                    y_vel *= -1;
                    return;
              }
    // Lets do the crazy furbidden
    x_vel = -1 * y_vel;
    y_vel = -1 * x_vel;
    return;
  }
        
          x = nx;
          y = ny;
      }

  }
  
function movementTick(){
  var len = particles.length;
      var dead = max_particles - len;
      for( var i = 0; i < dead && i < max_generation_per_frame; i++ ){
          particles.push(new Particle());
      }
    
// Update the date
now = Date.now();
dt = last - now;
dt /= 1000;
last = now;
particles.forEach(function(p){
  p.move(dt);
});
}

  function tick(){

      ctx.clearRect(0,0,width,height);
      particles.forEach(function(p){
      p.draw();
    });

      requestAnimationFrame(tick);
  }
  
this.start = function(){

  }
  
this.done = function(){

  }
  
setInterval(movementTick,16);
  tick();

})("loader");

Final Output:

Create a Love Loader using HTML, CSS, and JavaScript.gif

Conclusion:

In this tutorial, we've embarked on a creative journey to craft a Love Loader using HTML, CSS, and JavaScript. We've explored how this simple yet enchanting loading animation can transform your website's user experience, leaving a lasting positive impression on your visitors.


By now, you've learned the art of setting up the HTML structure, infusing it with style using CSS, and adding dynamic animation with JavaScript. You've discovered how to incorporate love-themed graphics, giving your Love Loader a personalized touch that aligns with your website's theme and message.


But our journey doesn't end here. As you deploy your Love Loader and continue refining your web development skills, remember that creativity knows no bounds. You have the power to innovate, iterate, and make your loader uniquely yours. Whether you're designing a personal blog, an e-commerce platform, or a portfolio site, a Love Loader can be that special touch that sets you apart in the digital landscape.


As you go forth, spread the love through your beautifully designed Love Loader. Enhance user engagement, evoke positive emotions, and make every visit to your website a memorable experience. Keep exploring, keep coding, and keep infusing your web projects with creativity and charm. The world of web development is yours to conquer, one Love Loader at a time. Happy coding!


Credit: Just a random person

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post