Ways to display or conceal a loading spinner using JavaScript

Whenever a button on my website is clicked, new content is loaded via ajax. To indicate that the content is being loaded, I created a div that contains a loading wheel graphic. In the function assigned to the button click event, I first add a class to the div to display the loading wheel, then load the content, and finally remove the loading wheel class. However, this process doesn't seem to be working as intended because the loading wheel does not appear at all. I even attempted to pause the JavaScript execution for a second before removing the loading wheel class, but the issue persists. For those interested in seeing a functional example, please refer to the jsfiddle link provided: http://jsfiddle.net/g8np7qLa/

Below is the corresponding JavaScript code:

function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

function show_loader(){
    $("#loader").addClass("loader");
event.preventDefault();
}


function hide_loader(){
    $("#loader").removeClass("loader");
event.preventDefault();
}

if($(".item-button").length) {


    $(".item-button").click(function(event) {
        show_loader();

    //load the ajax data
 wait(1000);
 hide_loader();

event.preventDefault();

    });


}

Answer №1

One great suggestion is to utilize the setTimeout function in your code:

$(".item-button").click(function(event) {
    show_loader();
    //load the ajax data
    //wait(1000);
    setTimeout(hide_loader, 1000);
    //hide_loader();
    event.preventDefault();
});

For a practical demonstration, refer to the following example:

function show_loader(){
$("#loader").addClass("loader");
  //event.preventDefault();
}

function hide_loader(){
$("#loader").removeClass("loader");
  //event.preventDefault();
}

if($(".item-button").length) {
$(".item-button").click(function(event) {
show_loader();
  //load the ajax data
    //wait(1000);
    setTimeout(hide_loader, 1000);
    //hide_loader();
    event.preventDefault();
});
}
.loader{
 position:fixed; top:0;
 left:0; right:0; bottom:0;     
 background:rgba(255,255,255,.8);
 /*padding-top:150px;*/
 padding-top:20px;
 z-index:99999;
}

.loader div{
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="loader">
  <div>

  </div>
</div>
<a href="#" class="item-button" data-item-name="itemname">
click here
</a>

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

Issue encountered with CSS-in-JS in a TypeScript, Webpack, React project: No matching overload found

My project involves Webpack, Typescript, and React Hooks with CSS-in-js for styling a div. I encountered an error while hovering over the style prop in the Menu component. I'm unsure about where to bind the CSSProperties. (JSX attribute) React.HTMLAtt ...

Unable to send a form through an Express/Angular application

I have a validation function in my program that prevents the form from submitting and displays an error message if there is an error. Otherwise, it will log "Success" to the console. However, I am unable to submit the form even when there are no errors. Is ...

The public folder in Node.js is known for its tendency to encounter errors

I'm facing an issue with displaying an icon on my website. Here is the current setup in my code: app.js const http = require('http'); const fs = require('fs'); const express = require('express') const path = require(&apo ...

The width of the absolute div shrinks to such an extent that the text starts wrapping around itself

My goal is to create a button that, when hovered over, displays a div. However, I am encountering challenges with the width and position of this div. The issue is illustrated in the images below and in the accompanying jsfiddle. When I set the positioning ...

Incorporating bcryptjs alongside MongoDB

I am currently developing a feature to securely encrypt user passwords using Bcrypt for my Angular application, which is integrated with MongoDB for the backend operations. Here is the implemented code snippet: Data Model var mongoose = require('mo ...

Steps for Enabling or Disabling a Bootstrap-Select Dropdown based on Radio Button Selection using JavaScript and jQuery

I am facing an issue with implementing two radio buttons and a Bootstrap-select Dropdown. I need to dynamically enable/disable the dropdown based on the selection of the radio buttons using JavaScript. Below is the HTML code snippet: Here is the code snip ...

Vue.js: Iterating over objects using v-for causes keys to be displayed in unexpected order

I've encountered an issue where Vue is not honoring the sequence of keys. The initial data I provide to the Vue component as a prop appears as follows: [ { id: 1, event_name: "event 1", scheduled_at: "2021-01-01" }, { id: 2, ev ...

Resolve memory leak issue with jQuery when returning an MVC partial view

I am developing an MVC application to display a table view. One of the columns in the table includes an action link that opens a jQuery UI dialog. After saving data from the dialog, I call the GridRefresh controller method which retrieves the newly saved d ...

Is there a way to transfer the lat, lng, and address values from a jQuery function to a PHP form, and then store all of this information in a MySQL table

Is there a way to pass the latitude (lat), longitude (lng), and address values from jQuery Google Maps functions (gmaps.js) to main.html? I want to gather these values, as well as others obtained in the main HTML, and display them together on a MySQL table ...

Using Redux to populate initial input values in React

Here's the situation - I have an input field where users can enter their email address. When they click 'save,' this email is stored in the database. The challenge I'm facing is that when the page is refreshed, I want the input field t ...

Developing a universally accessible variable for utilization in various functions

I'm having trouble understanding why 'currentPos.LatLng' is undefined when trying to access it outside the function even though it's part of an object. I want to be able to retrieve the current position values to use them in another fun ...

MathJax been harnessed for rendering LaTeX in web browsers in

My attempt to implement the library mathjax in Nuxt 3 was unsuccessful. <template> <div> <textarea v-model="formula"/> <vue-mathjax :formula="formula"/> </div> </template> ... /plugins i ...

What is the best way to change routes within my React application?

I am currently facing a challenge with the Routes in my work's web application. The existing method of accessing routes involves manually typing in the extended path in the browser, which is not ideal. I want to enhance this by adding new routes that ...

Could someone help me understand why changing the background color of the body element is causing my other CSS styles to not work as expected?

Why does setting the background color for my body in CSS ignore the styles that come after it? Can someone explain what is causing this issue and how to resolve it? body{ background-color:gray; }; h1 { text-align:center; } <html> < ...

Refresh a module variable or redefine a filter within AngularJS

Can a filter be dependent on a lazy-loaded value? In my scenario, a language pack is loaded asynchronously and the filter should only reflect the loaded values once they are available. // setting up the i18n filter app.filter('i18n', ['loc ...

Issue encountered when upgrading from Angular 4 to Angular 5: Module '@angular/router' is not found

I recently made the switch from angular 2 to angular 5. However, after the upgrade, I encountered some errors in my ts file. Should I remove @angular/core and @angular/router in angular 5? Here is a snippet of my package.json post-upgrade. Below are the de ...

Struggling to remove quotation marks from a string that was originally an array before being converted?

Here is the code snippet that I am struggling with: users = [{ "userid": "45", "name": "steve" }, { "userid": "32", "name": "john" }]; getuser = users.flatMap(user => user.userid === '32' ? user.name : []); result = getuser.toSt ...

Activate scroll event when image src changes in Angular using jQuery

Seeking assistance with utilizing jQuery to scroll to a specific thumbnail inside a modal when left/right arrows are pressed. The modal should appear when the user clicks on an image. I've managed to implement scrolling upon clicking a thumbnail, but ...

Attempting to configure the <img> element to automatically adjust its size in accordance with the page dimensions

<center> <img style="width: 100%; max-height: 100%" src="images/ratios/3to2ratio.JPG" /> This is a traditional 35mm Still Film ratio of 3:2. </center> Although this code allows the image to scale with the page size, I prefer ...

only displaying the months on the calendar widget

There is a specific condition in my code where, depending on the value entered, the jQueryUI datepicker will either display days or months. function setdate(q){ var d=new Date(); if (q==1){ var type={ ...