Is it possible to display or hide a spinner within a span using Javascript and AJAX?

When submitting a contact form, I want to display and hide a spinner on the submit button. The spinner should be visible while the form is being submitted and hidden once the submission is complete.

Below is the code for my submit button with the spinner:

<div class="d-flex justify-content-center">
  <button class="btn btn-medium btn-fancy btn-primary mb-0 ls-wider" type="submit" id="submitButton">
    <span class="submitSpinner spinner-border spinner-border-sm me-1"></span> Send Message
  </button>
</div>

Additionally, here is the AJAX function that handles the form submission:

$(document).ready(function() {
  $('.submitSpinner').css('display','none');
  $("#contact-form").submit(function(e) {
    e.preventDefault();
    $('#submitButton').text('Sending Message');    
    $('.submitSpinner').css('display','inline-block');
    var data = {
      'name': $('#name').val(),
      'email': $('#email').val(),
      'phone': $('#phone').val(),
      'company': $('#company').val(),
      'message': $('#message').val(),
    }
    $.ajaxSetup({
      headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
    });
    $.ajax({
      type: "POST",
      url: "/contact/message/send",
      data: data,
      dataType: "json",
      success: function(response) {
        if (response.status == 400) {
          $.each(response.errors, function(key, error) {
            $('#contact-alerts').append('<div class="col-12 col-md-9 col-lg-7 alert alert-danger alert-dismissible fade in show" role="alert"><button type="button" class="btn-close line-height-unset" data-bs-dismiss="alert" aria-label="Close" ></button>' + error + '</div>')
          });
          $('.submitSpinner').css('display','none');
        } else {
          $("#contact-form")[0].reset();
          $('#submitButton').text('Send Message');
          $('.submitSpinner').css('display','none');
          $.magnificPopup.open({
            showCloseBtn: true,
            items: {
              src: '#contact-success'
            },
            type: 'inline',
            fixedContentPos: false,
            fixedBgPos: true,
            overflowY: 'auto',
            closeBtnInside: true,
            preloader: false,
            midClick: true,
            removalDelay: 300,
            blackbg: true,
            mainClass: 'my-mfp-slide-bottom',
          });
        }
      }
    });
  });
});

Answer №1

a) It is important to place the spinner outside of the button element

b) Initially, add a class with CSS property display:none

c) Use .show() and .hide() methods to manage visibility

Here is a working example:

$(document).ready(function() {
  $("#submitButton").click(function(e) {
    e.preventDefault();
    $('.submitSpinner').show();
    setTimeout(
      function() {
         $('.submitSpinner').hide();
      }, 5000);
   
  });
});
.hide {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="d-flex justify-content-center">
  <button class="btn btn-medium btn-fancy btn-primary mb-0 ls-wider" type="submit" id="submitButton">Submit</button>
  <br>
  <span class="submitSpinner spinner-border spinner-border-sm me-1 hide">Send Message...</span>
</div>

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

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

Having trouble finishing the npm installation process

Having trouble with completing 'npm install'. Can someone please assist me?</p> <pre><code>Encountering a warning about an old lockfile while running npm install. The package-lock.json file was created with an outdated version o ...

Click on the entire Material-UI formControlLabel to select it, not just the text

I have recently started working with the material UI. Currently, I am dealing with a form that looks like this: <FormControl variant="outlined" className={css.formControl} margin="dense" key={"abc_" + index} > <FormControlLabel cont ...

The HSET command in the Redis client for Node.js is not working

I have been developing a DAO (data access object) for the project I am currently working on, which acts as an abstraction of a redis database. Below is the code relevant to my upcoming query: var redis = require("redis"); var _ = require("underscore"); va ...

Dynamic data binding in AngularJS with dynamically generated views

The scenario: Currently, I am constructing a wizard in AngularJS that contains tabbed content with each tab representing a step in the wizard. These steps are fetched from the database through a Laravel controller and displayed using ng-repeat. Each tab c ...

Searching for real-time data with ajax. Strategies for showing alternative results when there is no user input

I am currently working on developing a live search feature using technologies like ajax, jQuery, PHP, and MySQL. The user inputs certain queries which are then sent to form_livesearch.php where the search is processed. I have successfully implemented this ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

Is it possible to manipulate CSS on a webpage using javascript?

I have incorporated this piece of JavaScript to integrate a chat box onto my website: window.HFCHAT_CONFIG = { EMBED_TOKEN: "XXXXX", ACCESS_TOKEN: "XXXXX", HOST_URL: "https://happyfoxchat.com", ASSETS_URL: "https://XXXXX.cloudfront.ne ...

Developing entities in Express.js

My express app is currently fetching data from an external API through the following endpoints: api.com/companies (GET, POST) api.com/companies/id (GET, PUT) To improve maintainability and avoid code repetition, I am looking to create a model for handlin ...

bootstrap modal dialog displayed on the edge of the webpage

I am facing an issue with a modal dialog that pops up when clicking on a thumbnail. The JavaScript code I used, which was sourced online, integrates a basic Bootstrap grid layout. The problem arises when half of the popup extends beyond the edge of the pa ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Deactivate the submission button when there are no search results in typeahead.js

How can I disable the submit button if there are no search results found? The form should not be submitted in this scenario. I am currently using typeahead.js for my code. $('.typeahead').typeahead(null, { name: 'suburb', disp ...

Puzzling array challenge. Lack of clarity in explanation

I am currently working on a series of JavaScript tests available at js-assessment One of the tasks states: it("you should be able to find all occurrences of an item in an array", function() { var result = answers.findAllOccurrences('abcdefab ...

Iterating through a SASS map and retrieving the next item in the loop

I am working with a color array that looks like this: $colors: ( 'primary': '#aaa', 'secondary': '#bbb', 'color-3': '#ccc', 'color-4': '#ddd', 'color-5': & ...

How to implement the onRowClick event in ASP.NET Gridview to show record details without using a Details/Select button

I'm currently working with a gridView and have configured a button within it to display detailed information when clicked. This button calls the DetailsView() function, which executes an SQL command and binds the data to a repeater for a custom detail ...

In IE9, the margin: auto property does not effectively center a div element

I'm trying to center a content div in the space leftover by a sidebar. Here's how I want it to look: After some trial and error, I was able to achieve this for most browsers by using margin: auto on the specific div, along with setting overflow: ...

Navigating to User's Specific Info Page using Node.js

Would love some input on my current issue. I have a table featuring a list of users, and my goal is to display user information in detail whenever a user (which corresponds to a row in the table) is clicked. The process involves identifying which user was ...

Using jQuery on a pair of events

I want to enhance this jQuery function so that it executes both on page load and when the window is resized. jQuery(document).ready(function() { Maybe something along the lines of: jQuery(document).ready OR $(window).resize(function() { ...

What is the best way to display a Base64 image in a server-side DataTable?

This HTML code is designed to load server-side data into a table. The data is retrieved from the controller using AJAX requests. <script type="text/template" id="tablescript"> <td><%=Name%></td> <td><%=PhoneNumber%> ...

Amazon S3 Landing Page Featuring Contact Form

Although S3 is not a fileserver, it serves as an excellent tool for managing static websites. The majority of my projects are 99% static, making it ideal for this particular project. As an AWS Solutions Architect, I am struggling to find the most straightf ...