Ask Your Question

Revision history [back]

click to hide/show revision 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:

  1. Create a spinner element in your HTML code. This can be a simple div with a class name "spinner" or a complex SVG animation.

  2. Style the spinner using CSS, making it hidden by default:

    .spinner { display: none; /* Other styles */ }

  3. 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 });

  4. 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.