Categories
JavaScript Answers

How to show a spinner while loading an image via JavaScript?

Spread the love

Sometimes, we want to show a spinner while loading an image via JavaScript.

In this article, we’ll look at how to show a spinner while loading an image via JavaScript.

How to show a spinner while loading an image via JavaScript?

To show a spinner while loading an image via JavaScript, we add the spinner image and show it.

For instance, we write

<div><img src="spinner.gif" id="spinnerImg" style="display: none" /></div>

to add the spinner image and hide it by default.

Then we write

const hideSpinner = () => {
  document.getElementById("spinnerImg").style.display = "none";
};

const chartOnClick = () => {
  const spinnerShowTime = 3000;
  document.getElementById("spinnerImg").style.display = "";
  document.getElementById("chart").src = "/charts/10.png";
  setTimeout(hideSpinner, spinnerShowTime);
};

to load the image we want to show in the chartOnClick function.

We show the spinner with

document.getElementById("spinnerImg").style.display = "";

Then we load the image with

document.getElementById("chart").src = "/charts/10.png";

Then we the spinner in the hideSpinner function with

document.getElementById("spinnerImg").style.display = "none";

Conclusion

To show a spinner while loading an image via JavaScript, we add the spinner image and show it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.