There are several ways to include a loading spinner when a button is clicked, but here is a basic method using JavaScript and CSS:
Create a spinner element in your HTML code. This can be a simple div with a class name "spinner" or a complex SVG animation.
Style the spinner using CSS, making it hidden by default:
.spinner { display: none; /* Other styles */ }
Add an event listener to the button using JavaScript, which will show the spinner when the button is clicked:
const button = document.querySelector('#myButton'); const spinner = document.querySelector('.spinner');
button.addEventListener('click', function() { spinner.style.display = 'block'; // Execute the button's action // Hide the spinner when the action is complete });
Depending on your use case, you may want to hide the spinner when the button's action is complete. You can do this either by setting a time delay or by using a callback function.
Example:
button.addEventListener('click', function() {
spinner.style.display = 'block';
setTimeout(function() {
spinner.style.display = 'none';
// Execute the button's action
}, 2000);
});
This method shows the spinner for two seconds before hiding it again, but you can adjust the timing or use another method if needed.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-08 11:00:00 +0000
Seen: 13 times
Last updated: Jun 22 '21
What steps can I take to prevent my webpage from slowing down when all parts of a div are displayed?
How can Recursive Quote Embedding for HTML and Javascript be made more advanced?
When printing from WKWebView in Swift, the background is not taken into account.
Is it feasible to utilize a Toggle Button to switch among multiple classes exceeding 2?
What is the process for generating a dynamic subdomain/URL using vue.js?
How can I create a transition on click using CSS without the need for JavaScript?