Is there a way to seamlessly transition the visibility of the Bootstrap 5.3 Spinner as it loads and unloads?

After delving into some research regarding Bootstrap-compatible spinners, I stumbled upon a piece of code. Take a look:

function getData() {
            var spinner = document.getElementById("spinner");
            spinner.style.display = "block";
            setTimeout(function () {
               fetch("https://jsonplaceholder.typicode.com/posts")
               .then((response) => response.json())
               .then((data) => {
                  data.forEach((item) => {
                     var div = document.createElement("div");
                     var p = document.createElement("p");
                     p.innerText = item.title;
                     div.appendChild(p);
                     document.getElementById("dataContainer").appendChild(div);
                  });
                  spinner.style.display = "none";
               });
            }, 5000);
         }
         getData();

         <!-- begin snippet: js hide: false console: true babel: false -->
#spinner {
            position: absolute;
            top: 49%;
            left: 47%;
            width: 3.5rem;
            height: 3.5rem;
            /* transform: translate(-50%, -50%); */
            display: none;
         }
<!DOCTYPE html>
         <html>

         <head>
           <title>Bootstrap Spinner Tutorial</title>
           <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8defe2e2f9fef9ffecfdcdb8a3bda3bf">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
         </head>

         <body>
           <div class="spinner-border m-5" role="status" id="spinner">
             <span class="visually-hidden">Loading...</span>
           </div>
           <div id="dataContainer"></div>
           <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6e0c01011a1d1a1c0f1e2e5b405e405c">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
         </body>

         </html>

I aim to have it smoothly fade in and out for visual appeal. While I did come across some related queries here on StackOverflow, they didn't offer much assistance. Let me know if you have any suggestions or solutions.

Answer №1

Here is a simple solution using CSS transitions. By toggling the class "hidespinner", I can show or hide the spinner.

To better understand this trick with CSS animation, check out this article.

function fetchData() {
         var spin = document.getElementById("spinner");
         spin.classList.remove('hidespinner'); // <- new
         setTimeout(function () {
            fetch("https://jsonplaceholder.typicode.com/posts")
            .then((response) => response.json())
            .then((data) => {
               data.forEach((item) => {
                  var div = document.createElement("div");
                  var p = document.createElement("p");
                  p.innerText = item.title;
                  div.appendChild(p);
                  document.getElementById("dataContainer").appendChild(div);
               });
               spin.classList.add('hidespinner'); // <- new
            });
         }, 5000);
      }
      fetchData();

<!-- begin snippet: js hide: false console: true babel: false -->
#spinner {
  position: absolute;
  top: 49%;
  left: 47%;
  width: 3.5rem;
  height: 3.5rem;
  /* transform: translate(-50%, -50%); */
  /* new code */
  visibility: visible;
  opacity: 1;
  transition: visibility 0s linear 0s, opacity 300ms;
}

#spinner.hidespinner {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s linear 300ms, opacity 300ms;
}
<!DOCTYPE html>
<html>

<head>
  <title>Bootstrap Spinner Tutorial</title>
  <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0b2bfbfa4a3a4a2b1a090e5fee0fee2">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>

<body>
  <div class="spinner-border m-5 hidespinner" role="status" id="spinner"><!-- added class "hidespinner" here to initial hide the element -->
    <span class="visually-hidden">Loading...</span>
  </div>
  <div id="dataContainer"></div>
  <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="482a27273c3b3c3a2938087d6678667a">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</body>

</html>

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

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

Swap out a button for another using JavaScript

I am facing a challenge where I need to replace an active button with a deactivate button. The issue is that when I click on the active button, it does change to the deactivate button as expected. However, clicking again does not switch it back to the acti ...

Incorporating a hamburger symbol into an established menu for easy navigation

I have come across a tutorial on creating a navigation menu with a logo positioned to the left. However, I now wish to incorporate a hamburger icon for mobile devices and I am unsure about the process. Despite my efforts to find a suitable tutorial onlin ...

What is the best way to optimize my ExpressJS + Sequelize files for proper compatibility with Jest testing framework?

For the past few years, I have been developing an ExpressJS server application for internal use at my workplace. This application serves as a clinical decision support tool utilized in various hospitals. As the application has grown significantly in size, ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

What is the best way to include CSS code in the output display?

I'm looking to customize the appearance of my table rows and cells. Specifically, I want the cell file name, size, etc., to be colored blue while each row should have a different color on hover. I've attempted to achieve this using CSS and variou ...

Tips for inserting user input into an array and showcasing it

const [inputValue, setInputValue] = useState(""); return ( <input onChange={(event) => setInputValue(event.target.value)} /> <p>{inputValue}</p> ); I'm facing a problem where I need to take input from a user and store it in ...

What could possibly be causing my app to exhaust CPU resources on Mozilla Firefox?

I have created a unique game application for Facebook. Currently, the app is not optimized with AJAX technology, resulting in multiple server requests causing high CPU usage (specifically in Firefox) which slows down the overall performance of the app. Alt ...

Customizing colors for the progress bar in Angular Material

In my Angular 5 project, I am using a material progress bar and hoping to customize the colors based on the percentage progress. Despite trying various methods from other sources (including previous SO questions), I have been unsuccessful in getting it to ...

Calculating the size of grid thumbnails or items using the calc() function

I am currently working on building a responsive portfolio grid that spans the full width of the screen. To achieve this, I have set the width of the items using calc() and ensured that the thumbnail image fills the entire div by applying the following CSS: ...

Adjusting offcanvas height in Bootstrap based on content

.cursor-pointer { cursor: pointer; } <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="690b06061d1a1d1d09c13c809e9afbcfc1792efeff8">[email protected]</a>/dist/js/bootstr ...

The CSS styles for a:link, a:active, and a:visited do not seem to work with

My page contains the following CSS rule: a:link,a:active,a:visited{text-decoration:none;} I have encountered an issue where this rule is not working as expected. To apply the rule within a div with the id="test", I had to modify the rule like this: #tes ...

Display tables based on selected changes with dynamically changing options

My HTML structure displays rows with active and inactive statuses based on a select change, and it's currently functioning correctly. However, the project requirements have changed, allowing for more status options besides just active and inactive. I ...

Different ways to position two header tags on top of each other instead of next to each other

I am attempting to adjust the placement of my header tags so that the second header sits directly below the first one, rather than side by side. Currently, I am using h1 and h2 tags for my headers. I have experimented with placing both headers inside an h ...

Utilize Node.js and an API to generate a new problem in GitHub, but encountering an issue where the response

I have been experiencing an issue related to making a Post request to the Github API for creating an issue. I have gone through this post on Stack Overflow but I am seeking assistance in using the request module. Although I have referred to the Github docu ...

Showing JSON data as a table in an HTML format

After receiving the JSON String from the server as a response, which can be viewed here, I've implemented the following Jquery Code: function loadCategories() { $.ajax({ type: "POST", url: "/Services/ControllerService. ...

The json_encode() function returned a JSON that is not valid

In my PHP file (although more complex, even with the simplest code it fails), I have: <?php $salida = array(1,2,3,4,5); echo json_encode($salida); ?> The response received is: [1,2,3,4,5] While this appears valid, it's actually not. When pas ...

Can a Javascript file be concealed from view?

Imagine a scenario where the localhost root file is served an HTML file using the following code: app.get('/', (req, res) => res.sendfile('index.html')) Is it possible to include JavaScript files in the HTML document that are not a ...

Leveraging PHP functions for form validation

Previously, the code worked flawlessly until I integrated it into functions. Now, I am struggling to get this form to function correctly with the functions I created. It seems that passing variables and implementing the main logic are key steps, but I&apos ...

Dropdown menu will appear when you click on one of the menu items

Can someone help me create a dropdown menu using a JavaScript function that toggles on click? I've attempted to do so with the following code, but it's not working as expected. Could you please point out where I might be going wrong? I'm loo ...