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

What is the significance of receiving an error in Internet Explorer when running the code below?

function checkStepValidity(isValid, dataModel) { if (isValid) { updatedDataModel = mergeObjects(this.updatedDataModel, dataModel); } }, The code above encounters the following error in Internet Explorer / Edge browse ...

What is the best way to crop an image to focus solely on the center portion?

Using Bootstrap 3, how can I display an image cropped in a .col-sm-6 grid column? The image is 720px wide. Typically, with the .img-responsive class, the image will resize proportionally when the display size changes. However, I want to crop the left and ...

Is a Page Refresh Required to Reload Routes in ReactJS?

I have created menu links labeled Home, About, What I Do, and Experience for my portfolio site using BrowserRouter. However, when I click on these links, the components do not load properly on the page; they only render correctly after a page refresh. This ...

Utilizing Node.js to insert a new image path into MongoDB

I have successfully stored image paths in MongoDB in array format. Now, I need to figure out how to add another image path to the existing array using the document ID. How can I achieve this in MongoDB? Currently, I am uploading images using an HTML file. ...

Using Ajax to dynamically generate column headers in Datatables

Is there a way to create a header title from an ajax file? I've been trying my best with the following code: $('#btntrack').on('click', function() { var KPNo = $('#KPNo').val(); var dataString = & ...

Utilize jQuery to track and record AdWords conversions

I have noticed a number of inquiries regarding tracking Adwords conversions with jQuery on this platform. However, it appears that there is no definitive solution yet. My attempt at recording a conversion involves the code below following the submission o ...

What is the purpose of utilizing "({ })" syntax in jQuery?

What is the purpose of using ({ }) in this context? Does it involve delegation? Can you explain the significance of utilizing this syntax? What elements are being encapsulated within it? For instance: $.ajaxSetup ({ // <-- HERE error: fError, ...

Deleting lines from JSON object using Angular or JavaScript

On my webpage, I have a list where you can add a new line by pressing the "+" button (easy with push), but I'm not sure how to remove lines using the "X" button. https://i.stack.imgur.com/nm06A.png This is the JSON structure: "priceExtra" : [ ...

Verify the status of the internet button and display a message indicating whether it has been selected or not

I’ve been attempting to complete this task: opening this particular page in Python, and observing the outcome when the "Remote eligible" button is enabled; do any job positions appear or not? Here's the code I have so far, but it keeps throwing thi ...

Troubleshooting: Phonegap Not Responding to Ajax Requests

I've been trying to figure out how to make an ajax request work with PhoneGap, but I haven't had any luck so far. I'm using the latest version of PhoneGap and Android Studio. When I preview my app in AVD, everything looks good except for the ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

What is the best way to add padding to both the TextField input and label components within Material UI?

Recently, I've integrated Material UI into my project and set up a TextField for a form field. However, I'm facing an issue where applying padding to the input field doesn't affect the label as well. <TextField sx={{ display: &q ...

Can responsive images be utilized with a DIV's background-image property?

For my website, I want to incorporate a variety of Thumbnails that are retrieved from a database and displayed in different sizes within a Masonry grid. Typically, I would use background-image:url(image.jpg); background-size: 100% 100%:, but I am aiming t ...

JQuery AJAX responds with an error

I'm attempting to configure an ajax call using JQuery to access a specific URL. The URL I am targeting for the query is Here's what my jQuery code looks like: $.ajax({ url: "http://www.icis.com/rss/publicrss/", type: "GET", dataType: "xml ...

Not motivated to write HTML content

Recently, I've been utilizing the lazySizes plugin for optimizing my images. However, I encountered an issue when trying to implement it for HTML content display. Is there a simpler way to achieve this and maintain my current HTML structure? $(&apo ...

One way to position a sidebar between two divs is to ensure it adjusts seamlessly to the size of the browser window when resized

In my layout, I have two grids: one for the header and one for the footer. In between these two grids, I am using a sidebar on the left side. Below is the JavaScript code I am using: function adjustSize() { var heights = window.innerHeight; docum ...

Exploring the variations between getRequestHandler and render functions in Custom Next.js applicationsIn a

Greetings, I found it quite unexpected that there is a lack of information available on the functionalities of the getRequestHandler and render functions within the next package. As I am in the process of setting up a custom server, I am curious about wh ...

Monitoring and recording the current line number during evaluation

Recently, I've been experimenting with eval to modify a $scope object named variables. This is the watcher I'm using: $scope.$watch(function () { return $scope.variables; }, function (variables) { console.log('changed!'); }, true) ...

Clicking activates Semantic UI's dropdown function with the onClick method

I am experiencing an issue with the dropdown functionality on my website. Everything works fine until I add onClick() to the Semantic UI component. It seems like there are some built-in functions for handling onClick() within Semantic UI, so when I impleme ...

Step-by-step guide to minify Typescript files with Webpack

I am facing an issue in my webpack configuration while trying to minify the output bundle when working with TypeScript. Currently, only one file has been migrated to TypeScript in my project and it works fine with babel-node and the dev bundle without Ugli ...