1 | initial version |
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.