Search code examples
javascriptbootstrap-4

Displaying spinner onclick


I built a Spinner and animated it with CSS, and now I'm trying to hide the spinner and display it when the button has been clicked. So far,I have written this code and it doesn't show up when I click the submit <button>

I hid the spinner with display:none and tried to use JavaScript to change the <div> to display:block, but it doesn't work.

CSS:

* {
margin: 0;
padding: 0;
}

.loader {
   display: none;
   top: 50%;
   left: 50%;
   position: absolute;
   transform: translate(-50%, -50%);
}

.loading {
   border: 2px solid #ccc;
   width: 60px;
   height: 60px;
   border-radius: 50%;
   border-top-color: #1ecd97;
   border-left-color:  #1ecd97;
   animation: spin 1s infinite ease-in;
}

@keyframes spin {
   0% {
       transform: rotate(0deg);
   }
   100% {
       transform: rotate(360deg);
   }
}

JavaScript:

 function spinner() {
 document.getElementsByClassName("loader").style.display = "block";
 }

HTML:

<button type="submit" class="sbtn btn btn-secondary btn-c" 
onclick="spinner()" >Log in</button>

I'm new with Javascript so I figured I'd get some pointers here.


Solution

  • If you want to add a style to your spinner you have to get the first element returned by the function getElementsByClassName.

    getElementsByClassName returns a list with the elements with that specific class.

    getElementById returns one element, with the given Id.

    I sugest in your case, to give an ID to the loader and do getElementById. But if you want to use getElementsByClassName you can do the following:

    document.getElementsByClassName("loader")[0].style.display = "block";
    

    Here's a working spinet:

    * {
      margin: 0;
      padding: 0;
    }
    
    .loader {
      display: none;
      top: 50%;
      left: 50%;
      position: absolute;
      transform: translate(-50%, -50%);
    }
    
    .loading {
      border: 2px solid #ccc;
      width: 60px;
      height: 60px;
      border-radius: 50%;
      border-top-color: #1ecd97;
      border-left-color: #1ecd97;
      animation: spin 1s infinite ease-in;
    }
    
    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }
    
      100% {
        transform: rotate(360deg);
      }
    }
    <button type="submit" class="sbtn btn btn-secondary btn-c" onclick="spinner()">Log in</button>
    <div class="loader">
      <div class="loading">
      </div>
    </div>
    
    
    <script type="text/javascript">
        function spinner() {
            document.getElementsByClassName("loader")[0].style.display = "block";
        }
    </script>