javascript loading animation on button click

JavaScript Loading Animation on Button Click

As a web developer, you might have come across situations where you need to display a loading animation when a user clicks on a button. This is especially useful when the action triggered by the button takes some time to complete, and you don't want the user to think that the page has frozen.

One way to achieve this is by creating a CSS animation and triggering it using JavaScript:


const button = document.querySelector('button');
const loading = document.querySelector('.loading-animation');

button.addEventListener('click', () => {
  loading.style.display = 'block';
  
  // Your code to perform the action goes here
  
  loading.style.display = 'none';
});

In this code, we first select the button and the loading animation element using the document.querySelector method. Then, we add an event listener to the button for the 'click' event, and inside the callback function, we set the display property of the loading animation to 'block' to show it.

After that, we perform the action that we want to trigger when the button is clicked. This could be making an API call, fetching data from a database, or any other time-consuming task. Once this task is complete, we set the display property of the loading animation back to 'none' to hide it.

Another way to achieve this is by using a third-party library like Spin.js:

Spin.js is a lightweight JavaScript library that helps you create spinner animations. You can use it to show loading animations when a user clicks on a button.


const button = document.querySelector('button');

button.addEventListener('click', () => {
  const spinner = new Spinner().spin();
  document.body.appendChild(spinner.el);
  
  // Your code to perform the action goes here
  
  spinner.stop();
});

In this code, we first select the button using the document.querySelector method. Then, we add an event listener to the button for the 'click' event, and inside the callback function, we create a new instance of the Spinner class and call its spin method to show the spinner animation.

We then append the spinner element to the body of the document using the appendChild method. After that, we perform the action that we want to trigger when the button is clicked, and once this task is complete, we call the stop method of the spinner object to hide the spinner animation.

Overall, there are many ways to create loading animations on button click using JavaScript. You can either create your own CSS animations or use a third-party library like Spin.js. Whichever method you choose, make sure that the loading animation is displayed clearly to the user and that it gives them an indication that something is happening in the background.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe