DEV Community

Codewithrandom Blogs
Codewithrandom Blogs

Posted on

How To Add Loading Spinner In JavaScript?

Hello Coder,Welcome to the Codewithrandom blog. In Today's Blog We are going to see How to Create and Add To Loading Spinner Using JavaScript. this is Infinity Loading Spinner so you Can Adjust Yourself and Add Using JavaScript. 

Now The Project is going to create and for that, we are first adding an HTML Code for loading spinner.

HTML Code:

<div id="spinner"></div>
Enter fullscreen mode Exit fullscreen mode

Here a single line of HTML code is enough to add an spin loader. Simply a div class with name on it.

Now we are adding background using CSS.

CSS CODE:

html,body {
  margin:0;
  background:rgba(0,0,0,0.9)
}
Enter fullscreen mode Exit fullscreen mode

Calling out HTML and BODY we are fixing the margin value to zero and background using RGBA Property. Now for adding loading spin to explore load animation we are using Java Script.

Loading Spinner Javascript Code:-

but 1st add this cdn link to your project as in the script tag of javascript

https://cdnjs.cloudflare.com/ajax/libs/spin.js/2.3.2/spin.min.js
Enter fullscreen mode Exit fullscreen mode

Now add this js code to your js file

let opts = {
 lines: 13,
 length: 28,
 width: 14,
 radius: 42,
 scale: 1,
 corners: 1,
 color: '#FFF',
 opacity: 0.25,
 rotate: 0,
 direction: 1,
 speed: 1,
 trail: 60,
 fps: 20,
 zIndex: 2e9,
 className: 'spinner',
 top: '50%',
 left: '50%',
 shadow: false,
 hwaccel: false,
 position: 'absolute',
},
 target = document.getElementById('spinner'),
 spinner = new Spinner(opts).spin(target);
Enter fullscreen mode Exit fullscreen mode

In this JavaScript code , First we are creating an variable with target and getting the ID using get element by id property. Then again we creating an variable spinner and adding new spinner object and passing a OPTS variable that contains values for making load spin and the spin(target) is called out.

The values like length , width , height , color, rotate etc... is added to complete the load spin.

Now We have completed our Project successfully By adding source codes. So we can move for project preview in the given Output section.

Now We have Successfully Add Loading Spinner Using JavaScript. You can use this project for your personnel needs and the respective lines of code are given with the code pen link mentioned below.

If you find out this Blog helpful, then make sure to search Codewithrandom on google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

REFER CODE - Hexr

WRITTEN BY - Ragunathan

Top comments (0)