Showing loading spinner when clicked

I created a spinning animation in CSS, but now I want to hide it and only display it when a button is clicked. I've tried to achieve this using the following code, but the spinner doesn't appear when I click the submit button.

To hide the spinner initially, I used the CSS property display:none. Then, I attempted to use JavaScript to change the display property to block when the button is clicked, but it's not working as expected.

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 still learning JavaScript, so any advice or guidance would be greatly appreciated.

Answer №1

To customize your spinner, you need to target the first element that matches the specified class using the getElementsByClassName function.

The getElementsByClassName method returns an array-like object containing all elements that have the specified class name.

On the other hand, the getElementById function retrieves an element with a specified id.

In your case, I recommend assigning an ID to the loader and then using getElementById. However, if you prefer to use getElementsByClassName, you can achieve the same by accessing the first element in the array like so:

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

Here is a sample snippet demonstrating how to style a spinner:

* {
  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>    

Answer №2

Could you specify where you would like the spinner to be added? In the meantime, I have created a <div> element to contain the spinner's animation as shown below:

HTML:

<button type="submit" id="btn" class="sbtn btn btn-secondary btn-c">Log in</button>

<div class='spinner-displayer'></div>

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() {
    const spinnerDisplayer = document.querySelector('.spinner-displayer');
    const btn = document.getElementById('btn');

    btn.addEventListener('click', () => {
    spinnerDisplayer.classList.add('loading');
  })
}

spinner();

Feel free to explore this live code demo.

As a best practice, I recommend avoiding the use of inline event handlers in your HTML code, as it is considered a less favorable approach.

Answer №3

If you're looking for a solution, check out this code snippet here: https://codepen.io/jmalatia/pen/HkmaA

<div style="margin:3em;">
<button type="button" class="btn btn-primary btn-lg " id="load" data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Processing Order">Submit Order</button>
<br>
  <br>
<button type="button" class="btn btn-primary btn-lg" id="load" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Processing Order">Submit Order</button>



$('.btn').on('click', function() {
    var $this = $(this);
  $this.button('loading');
    setTimeout(function() {
       $this.button('reset');
   }, 8000);
});

</div>

Answer №4

It can be challenging to understand the purpose of the loader class without the complete html code.

<div id="loader" class="loading">
</div>
<button type="submit" class="btn btn-primary btn-custom" 
onclick="showLoader()" >Submit</button>


<style type="text/css">

    #loader {
        display: none;
    }

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

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

<script type="text/javascript">
    function showLoader() {
        document.getElementById("loader").style.display = "block";
    }
</script>

I have defined an ID of #loader for the spinner element and set its display to none initially. Upon clicking the button, the display is changed to block.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to incorporate an icon into a React Bootstrap Dropdown menu

I'm struggling to figure out how to include an icon in my react dropdown button, similar to the one shown in the following example. https://i.sstatic.net/cn0b0.png The react bootstrap package I am currently using does not seem to offer a straightfor ...

utilize JavaScript on every element that has a specific identifier

<a id="link" href="http://www.google.co.uk">link</a> <a id="link" href="http://stackoverflow.com">link</a> Is there a way to make the JavaScript code apply to all <a> tags with the id="link", instead of just the first one? A ...

Troubleshooting a JavaScript Error on an ASP.NET MasterPage

After implementing the following JavaScript code: <script type="text/javascript> $(document).ready(function () { $('#social-share').dcSocialShare({ buttons: 'twitter,facebook,linkedin,di ...

I'm having trouble with the pull-right feature in Bootstrap -

I am having trouble with the bootstrap class pull-right. Despite applying it, my span is still floating to the left. I am unsure why the pull-right class is not functioning as expected. <!DOCTYPE html> <html lang="cs"> <head> <me ...

Transfer the value of a JavaScript variable to paste it into a fresh tab on Google Chrome

I have come across some examples where users can copy HTML text to the clipboard. However, I am working on something more dynamic. Here's what I'm trying to achieve: <button id="" ng-click="outputFolder()">Output Folder</button> $sc ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

What is the purpose of using async/await in Node.js when it is inherently asynchronous, and in JavaScript as well, vice versa?

Apologies for my lack of experience in Javascript and NodeJS. I'm a total beginner, so please excuse my silly questions. I've been trying to wrap my head around the concept but haven't found a clear explanation. Here's what's conf ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

import a dynamically created STL file

After creating an stl file from an uploaded file using JavaScript, I am facing an issue when trying to display it using three.js. Here is how I attempted to load the stl file: loader.load(my_generated_stl_string, function (geometry) { ... } Unfortunatel ...

Issues have been observed with the functionality of the Node.js EventEmitter when attempting to

Here's the issue: I have a class called save.js that inherits from EventEmitter. Here's how it looks: var util = require('util'); var EventEmitter = require('events').EventEmitter; var save = function(pdf){ var ...

The request to check the API at http://localhost/v5/api/checker returned a 404 error, indicating that

Trying to create a function that uses AJAX to call PHP, but encountering an error when clicking the button. Does anyone know how to solve this issue? Code provided below. PHP: $app->get('/checker', function () { $jsonContents = file_get_ ...

What is the best way to distinguish between relative blocks and convert them to absolute positioning?

What is the best way to locate relative blocks and convert them to absolute position while keeping them in the same place? Is this something that can be achieved using JavaScript or jQuery, or is it simply not possible? Thank you very much. ...

When clicking on HTML input fields, they do not receive focus

I am facing a puzzling issue where I am unable to access the input fields and textareas on my HTML form. The JS, HTML, and CSS files are too large for me to share here. Could someone provide guidance on what steps to take when troubleshooting this unusual ...

What is the best way to trigger a 'Save As' dialog box on a browser when a button is activated within an Angular application, guaranteeing cross-browser compatibility?

The solution needs to be compatible with both Windows and Mac operating systems. Additionally, we should be able to specify a default file name and type. ...

Ways to showcase HTML content in angular when receiving entities

Is there a way to properly display HTML characters using HTML entities? Take this scenario for example: Let's say we have the following string: $scope.myString = "&lt;analysis mode=&quot;baseball&quot; ftype=&quot;&quot; version ...

What is the process for converting the color names from Vuetify's material design into hexadecimal values within a Vue component?

I'm looking to obtain a Vuetify material design color in hexadecimal format for my Vue component's template. I want to use it in a way that allows me to dynamically apply the color as a border, like this: <div :style="`border: 5px solid $ ...

"Searching for existing data in MongoDB upon click event from the client side: A step-by-step guide

I have developed an express app that allows users to search for movies and add them to lists. If a movie is already added to the list, I want to show 'Already added' instead of 'Added to list'. How can I achieve this functionality from ...

Utilizing Bootstrap to display selected portions of the list content

I am working with a select element that looks like this: jQuery('.my-select').selectpicker(); .list_img{ width: 30px; height: 30px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script ...

What could be causing the Fontawsome icon to malfunction within a Bootstrap table item?

I am currently utilizing Fontawsome free version 5.15.4, along with Bootstrap 5.1 to develop a table using JavaScript. let newBtn = createAnyElement("button", { class: "btn btn-success", onclick: "createUser(this)&q ...

Struggling to get Angular to properly sanitize inputs using ng-bind-html

I've been struggling to figure out the issue in my code for an entire day with no success. At this point, I'm reaching out for help. My problem arises when trying to utilize ng-bind-html-unsafe within a template. As a newcomer to Angular, it&apos ...