DEV Community

Displaying a css spinner on ajax calls with fetch api

Kelvin Wangonya on February 01, 2019

I always have to search for how to do this or refer back to my previous code whenever I work with fetch. For a while, I've used the solution to thi...
Collapse
 
moopet profile image
Ben Sinclair

This is largely irrelevant to your post :), but you can replace

  spinner.className = "show";
  // ...
  spinner.className = spinner.className.replace("show", "");
Enter fullscreen mode Exit fullscreen mode

with

  spinner.classList.add('show');
  // ...
  spinner.classList.remove('show');

Enter fullscreen mode Exit fullscreen mode

which I think makes things a little easier to read and won't interfere with any existing classes.

Collapse
 
wangonya profile image
Kelvin Wangonya

Very nice. Didn't know about that 😀

Collapse
 
link2twenty profile image
Andrew Bone

Getting JavaScript to interact with CSS is a really good way to handle this.

Just for personal preference, I'd probably use the built-in hidden attribute, rather than having a show class. I'd also animate as small an area as possible by moving the spinner to a pseudo-class.

Great work 🙂

Collapse
 
codeonjim profile image
CodeOnJIm

Oh this is good! spinner is gone as the promise is resolved!

Collapse
 
banjuare_obi profile image
Obi Pascal Banjuare

Nice I love to have script on my newly develop blog site.

Collapse
 
bgadrian profile image
Adrian B.G.

You did a common mistake, to not hide the spinner at error, see promise.catch().

I know that error handling is a tabu subject in the JS ecosystem, but we should change this.

Collapse
 
wangonya profile image
Kelvin Wangonya

Didn’t know about promise.catch. I’ll check it out. Thanks!

Collapse
 
clarachaouat profile image
Clara Chaouat

Thanks a lot ! Very clear explanation

Collapse
 
shub78910 profile image
Shubham Hirakki

But then, there's a catch. How is it related to the time of loading data. As in, it will always load for 5 seconds irrespective of the actual loading time, isn't it?

Collapse
 
codeonjim profile image
CodeOnJIm

ya.he just put it there for demonstration.

Collapse
 
kasimsn profile image
Kasim ŞEN

Thank you very much bro. It's easier than I thought.

Collapse
 
bhupendra1011 profile image
bhupendra

Great .Is there a way to change the loading icon animating speed based upon the content fetched uptill now . Should spin fast if content is about to fully download