Displaying loading animation on Fetch API calls

vaishnavs

Vaishnav

Posted on December 2, 2020

Displaying loading animation on Fetch API calls

In web development, one of the most important part is to use REST api. When I start working on api with vanilla JS, I noticed small time difference between call and response. It's good practice to show end user something is happening after his interaction with website.
So here's the guide of showing loading animation on fetch api calls with vanilla JS.
Let's get started

HTML

Let's start with html.

HTML
<textarea> to get user input.
<button> to submit data.
<h1> to display response.

We are displaying loading animation using <div id="loading"></div>. This element is hidden by default. We are going to manipulate it, to show or hide it according our requirement.

Creating loader animation CSS

Stylesheet for loader

Working with Javascript

JS First part

In function displayLoading():

  • loader.className = "display"; this will add display class to
    <div id="#loading"></div>, which turn visibility: visible;

  • We are using setTimeout to hide loading animation after 5 second. Sometimes we may get late response, then timeout time should be increased.

Now, when displayLoading() called it will display loading animation and when hideLoading() called it will hide loading animation setting visibility: hidden;

Now for remaining JS
This part is straight forward. fetchHandler() to fetch data from api.

url I'm using is dummy url which only return 'Testing, you are' for any input.

JS second part


Here's the pen.

Hey there, I'm #codenewbie, started documenting my journey of learning. Any suggestions are welcome

πŸ’– πŸ’ͺ πŸ™… 🚩
vaishnavs
Vaishnav

Posted on December 2, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related