Show or conceal a bootstrap spinner using a function

Quandary I am facing an issue with displaying a bootstrap spinner while a function is running. The spinner should be visible during the execution of the function and disappear once it is done.

Here is the code for the bootstrap element:

<div id="resultsSpinner" class="spinner-border" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>

The CSS styles for the spinner are as follows:

.spinner-border {
    width: 3rem;
    height: 3rem;
    display: none; /* Initially set to not display */
}

Next, here is the JavaScript code I am using:

function performAction() {
    // Function logic goes here
    
    const spinnerElement = document.querySelector('.spinner-border');

    spinnerElement.style.display = 'initial'; // This should change the display property to show the spinner
}

The issue I am encountering is that the spinner is not displaying at all with the current setup. It does show up when I remove 'display: none;' from the CSS file, but that is not the desired behavior...

Attempted Solutions I have tried various ways to make the spinner display correctly, but none have worked so far. One approach I experimented with is the following, but it did not yield any success:

function showSpinner() {
        $(".spinner-border").fadeIn();
};
showSpinner();

Any guidance on resolving this issue would be greatly appreciated. Thank you in advance.

Answer №1

Customized HTML Code:

<div id="resultsSpinner" class="spinner-border" role="status">
                <span class="spinner spinner-border spinner-border-sm mr-3" role="status" aria-hidden="true">Loading...</span>
</div>

Include CSS in your stylesheet:

.spinner {
    display: none; 
}

body.busy .spinner { display:block !important; }

Alternatively, use visibility property:

.spinner { visibility:hidden; } 
body.busy .spinner { visibility:visible !important; }

JavaScript function to toggle class:

$(document).ready( function()
{
  $('.spinner-border').on('click', function()
  {
    $('body').addClass('busy');
  });
}); 

Remove 'busy' class when task is completed:

$('body').removeClass('busy');

Answer №2

Check out this suggestion:

const loader = document.getElementById('spinner');
loader.style.display = 'none' # hide the loader

# event listener for your button function
document.getElementById('funcButton').addEventListener("click", () => {
    loader.style.display = 'inline-flex' # show the loader

    button_function() 

    # if your button_function is an asynchronous function, avoid hiding the loader here:
    loader.style.display = 'none' # omit this line here! 

});


const button_function = async () => {
    
    # perform fetching or other blocking actions
    
    # at the end of the function, hide the loader
    loader.style.display = 'none' 

};

The issue is that the asynchronous function is non-blocking, causing the loader to appear and disappear quickly without a noticeable display.

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

The image displaying "Loading" fails to appear

My webpage includes a div styled with the following CSS: .modal { display: none; position: fixed; z-index: 1000; top: 0; left: 0; height: 100%; width: 100%; background: rgba( 255, 255, 255, .35 ...

What is the technique for determining the scale percentage of an image with the background-size property set to cover?

I am trying to determine the scale of an image after it has been resized. By using background-size: cover on the body background image, I want to ensure that the image maintains its aspect ratio and expands or shrinks to fit both the width and height of t ...

What is the process for completing a form and then going back to edit the data in PHP?

I am having trouble filling out a form and then being able to make changes to the entries later. However, every time I go back to modify the records, I want the form to still have the previous values intact. Unfortunately, when I tried putting " /> An ...

What strategies can be employed to maintain reliable datetime management for a reservation system operating in diverse time zones?

Looking at the big picture: An interesting scenario arises when a hotel owner specifies a time frame for booking reservations at a restaurant (5pm - 10pm). Along with this information, there is also a timezone provided to ensure that dates are displayed i ...

When I decide to incorporate both BootstrapVue and Vuetify CSS frameworks into a single project

Can I incorporate two CSS frameworks into my current Nuxt.js project? Does anyone have any insight on why it might be beneficial to use two different CSS frameworks in a Vue.js project? Please provide some guidance on this matter. I am looking to optimize ...

Extracting multiline value from a textarea using JavaScript

I'm trying to extract a multiline value from a textarea using JavaScript or jQuery and store it in a cookie. Below is the code snippet I am using: HTML: <textarea id="cont" cols="72" rows="15"> JavaScript: var txt = $('#cont').val( ...

Issues with the alignment of columns using Bootstrap framework

I've created a design in Photoshop using the Bootstrap 12-column guide, but when I try to implement it using Bootstrap, the results are completely off. https://i.stack.imgur.com/vQwOt.png Here's my HTML code: <!DOCTYPE html> <html lan ...

Exploring the functionality of arrays in Jest's cli option --testPathIgnorePatterns

Looking to exclude multiple folders, one in the src folder and another in node_modules, when using the --testPathIgnorePatterns option. Does anyone have an example of how to use this pattern effectively? I am unable to configure an array in the package.js ...

Using jQuery to create transitions when a class is changed and adding a delay to the transition

If you want to check out the section I created on CodePen, feel free to visit it by clicking here. I've noticed that my JavaScript code has a lot of repetitive elements and I'm looking to optimize it for better performance. Any advice on how I c ...

when the AJAX request has a specific condition

When making an AJAX request, I want to pass data only if a certain condition is met. The "data: testobj" line represents a JSON object that will return {"name":"tom"} $.ajax({ type: "POST", url: 'test.asp', data: testobj, succes ...

Is there a way to adjust the label elevation for a Material UI TextField component?

I am trying to enhance the appearance of a textfield label, but I am facing some challenges with my code. textStyle: { backgroundColor: '#1c1a1a', border: 0, borderRadius: 0, width: 400, height: 66, display: 'flex&a ...

The Laravel return view function seems to be malfunctioning as it is displaying an error page instead

I am facing an issue where I am trying to display an existing view but instead of the show page, I keep getting a "404 not found" error. As a beginner in Laravel, I am still trying to grasp its concepts. Any insights into why I am encountering the error 40 ...

Ways to customize tab display in Bootstrap 5

I am encountering an issue with my code that was previously functioning correctly in Bootstrap 3.3: $('#rides-tab').tab('show'); After upgrading to Bootstrap 5, I am now receiving an error ('tab' is not a function). I have at ...

Why isn't Gzip compression working in webpack? What am I missing?

After comparing the compression results of manual webpack configuration and create-react-app for the same application, it became clear that create-react-app utilizes gzip compression, resulting in a significantly smaller final bundle size compared to manua ...

Navigating in React: A Guide to Switching Components

I'm currently working on a landing page project using React. The goal is to have a consistent navigation bar across all sections of the website, with only the active state changing based on user interaction. Within my App.js file, I've implement ...

Best practices for managing CSV files in Next.js with TypeScript

Hello, I am currently working on a web application using nextjs and typescript. One of the features I want to implement is a chart displaying data from a csv file. However, I am not sure if using a csv file is the best choice in the long run. I may end up ...

Show the current range slider value using simple_form and bootstrap styling

I am trying to find a way to show the current value in a simple_form range input field. <%= f.input :data, as: :range, prompt: "my data", collection: 0..45 %> Unfortunately, I have not been able to find any information on this in the docum ...

When making an Ajax post request, the loading indicator may not appear

I've implemented the jQuery code below for an autocomplete input field, but I'd like to have a spinner display while waiting for the response from the server. In my code, I'm using search: to show the loading div and open: to hide it. The s ...

utilize ajax success method to extract json data

I'm currently working on displaying and parsing JSON data in the success function of an AJAX call. This is what I have so far: AJAX: data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val(); alert(data); url= "/portal/getRe ...

Do I need to manually destroy the directive scope, or will Angular take care of it

I have a question about directives in Angular. Let's say we have a directive called "myDirective". Here is the corresponding HTML: <div my-directive> </div> When we remove this <div> element from the DOM, will Angular automatically ...