Dunc
Dunc

Reputation: 33

I have a js script which should disable a button but it's not working

I have a button which makes an image spin for 3s. I want the button to be disabled during the spinning. But this is not working. Below are the js functions and the css class which creates the spin.

   <script>
    function spin() {
      document.getElementById("spin_switch").disabled = true;
      document.getElementById("image-map").classList.toggle("spin");
      setTimeout(stop_spin, 3000);
      document.getElementById("spin_switch").disabled = false;
    }
    function stop_spin() {
      document.getElementById("image-map").classList.toggle("spin");
    }
   </script>
    
   <style>
    .spin {
      transform: rotate(360deg);
      webkit-transform: rotate(360deg);
      overflow: hidden;
      transition-duration: 3s;
      transition-property: transform;
    }
   </style>

Upvotes: 2

Views: 78

Answers (1)

Đinh Carabus
Đinh Carabus

Reputation: 3496

You have to move this line

document.getElementById("spin_switch").disabled = false;

into the stop_spin function:

function spin() {
   document.getElementById("spin_switch").disabled = true;
   document.getElementById("image-map").classList.toggle("spin");
   setTimeout(stop_spin, 3000);
}
function stop_spin() {
   document.getElementById("image-map").classList.toggle("spin");
   document.getElementById("spin_switch").disabled = false;
}

Otherwise the spin_switch will be enabled again immediately. setTimeout does not stop the entire script. It just registers a callback to be executed after the given timeout has expired.

Upvotes: 1

Related Questions