How to show a spinner while loading an image via JavaScript
javascriptHere is an example of how you can show a spinner while loading an image using JavaScript:
// create a new image element
const imageElement = document.createElement('img');
// create a spinner element
const spinnerElement = document.createElement('div');
spinnerElement.innerHTML = 'Loading...';
// set the spinner as the content of the image element while the image is loading
imageElement.onload = () => {
// remove the spinner once the image has finished loading
spinnerElement.remove();
};
imageElement.onerror = () => {
// remove the spinner if there was an error loading the image
spinnerElement.remove();
};
// set the spinner as the content of the image element
imageElement.innerHTML = spinnerElement.outerHTML;
// set the src of the image element to start loading the image
imageElement.src = 'https://example.com/image.jpg';
// append the image element to the document
document.body.appendChild(imageElement);
This will show the spinner while the image is being loaded, and remove the spinner once the image has finished loading or if there was an error loading the image.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame