During the .each iteration, the change in div class isn't appearing

I have a JavaScript function that is activated by clicking a button. Before entering an 'each' loop, I add a class to an element.

When I run the code on the page, I don't see any changes. However, when I pause the code in the debugger, the changes become visible.

The code structure looks like this:

$("#btnApplyDefaults").on('click',
        function (e) {
    $('#loader').addClass("loading-page");
    $('#pricingSheetItems tr').filter(':has(:checkbox:checked)').each(function() {
        // Do something
    });
    $('#loader').removeClass("loading-page");
});

If I execute this with data that takes a long time to process, the loading image never appears. But if I set a breakpoint and step through the code, then I can see the image.

This is the CSS class being used:

div.loading-page {
    position: absolute;
    left: 50%;
    background-image: url("../../dist/img/loading.gif");
    background-repeat: no-repeat;
    content: "";
    display: block;
    width: 32px;
    height: 32px;
}

The class is assigned to this div:

<div tabindex="-1" class="" id="loader"></div>

Answer №1

Your code is currently running synchronously, which means it completes all tasks before allowing the UI to respond. By adding the loading class at the start, performing operations, and then removing the class, the UI does not get a chance to update in between.

To ensure your UI updates properly, you can introduce a slight delay using setTimeout:

 $("#btnApplyDefaults").on('click',
        function (e) {
    $('#loader').addClass("loading-page");
    setTimeout(function () {
        $('#pricingSheetItems tr').filter(':has(:checkbox:checked)').each(function() {
            // Perform necessary actions
        });
        $('#loader').removeClass("loading-page");
    }, 0);
});

While this approach may display the loading class, animations may not be smooth due to page computations. Consider exploring options like WebWorkers or asynchronous workers for a smoother user experience.

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 feature of window.open and pop-up blocker integrated into the $.ajax().done() function is

When my jQuery ajax call is completed, I need to open a URL in a new tab. Here's the function I created for this purpose: var openNewTab = function() { window.open('/UrlToOpen', '_blank'); win.focus(); } If I directly cal ...

Errors in production arise from building React applications

I am new to using React and recently built a ToDo web app following a tutorial. Everything seemed fine during development, but when I tried to view the production version locally using serve -s build, two errors popped up that were not present before. reac ...

How can a list of objects in a JPA entity with a many-to-one relation to a data entity be sorted based on the result of a method call from the data entity?

In my JPA entity User, there is a OneToMany relation to a UserStats entity. I made changes to the code to use UserStats instead of storing victoryRatio directly in the User entity. Now, calculateVictoryRatio() method is implemented in the UserDetails entit ...

The order of array elements in the AJAX server response appears to have been altered when accessed on the client side

After receiving a JSON response from my server side, the content looks like this - echo json_encode(array("result"=>"success", "networks" => $adNetworkListFinal)); For example, the value of $adNetworkListFinal is as follows - Array ( ...

Is it possible to retract a message on Discord after it has been sent?

I have a code that automatically sends a welcome message when a new member joins the guild, and I want it to be deleted shortly afterwards. Here is my current code: client.on('guildMemberAdd', (member) => { var server = member.guild.id; i ...

An issue arises in Node.js and MongoDB where data is being returned from the previous update instead of the most

Currently, I'm delving into the world of Node.js and creating a platform where individuals can vote on different items and view the results afterward. The voting process involves utilizing the /coffeeorwater POST route, which then redirects to the /re ...

Adjust the dimensions of polymer components (checkbox)

When attempting to adjust the size of the paper-checkbox, I experimented with changing the width and height properties in my CSS file. Additionally, I tried using transform: scale(2,2). The scale property resulted in blurriness, while adjusting the width ...

Listening for select elements that have remained unchanged

My current situation involves a select box with predetermined options. One of these options is preselected when the page loads: <select name="select" class="js-choice-select"> <option value="option-1">Option 1</option> <option ...

Maximizing the efficiency of React.js: Strategies to avoid unnecessary renders when adding a new form field on a webpage

Currently, I have a form that consists of conditionally rendered fields. These components are built using MUI components, react-hook-form, and yup for validation. In addition, within the AutocompleteCoffee, RadioBtnGroup, and TxtField components, I have i ...

The variable is unable to be accessed within the PHP function query

After passing a variable through ajax to a function within my php file "Cart_code.php", I encountered an issue where the variable was not accessible inside the function. Can you help me figure out why? Javascript $.ajax({ type: "POST", url: "incl ...

Issue with vue-cli3 eslint and compiler arising from conflicting vue/script-indent settings

Whenever my .eslint.js file includes this rule: "vue/script-indent": [ "error", 4, { "baseIndent": 1, "switchCase": 1, } ] and I save it, an error pops up: Error: Expected indentation of 32 spaces but only found 24 spaces ...

Bootstrap 4 experiences issues with modal dialogs

I am experiencing an issue with my code not working on Bootstrap 4. When I click on the 'overview' button, the page darkens but the dialog does not appear. This functionality worked fine with the old version of Bootstrap. Can someone please assis ...

Select from a dropdown menu with a single click

Need help with my dropdown menu. I'm having trouble getting it to hide when clicking on another element (menu), and the hover effect on the main menu does not stay while the dropdown is open. $('.menus >li').on('click', '& ...

How can you navigate to the left within a component by scrolling?

My Panel component is equipped with an overflow-x: scroll; feature for horizontal scrolling. Given the large amount of data it contains, I am looking for a way to enable horizontal scrolling within the panel. What is the best approach to achieve this? Is ...

Every DIV is filled with HTML and CSS

My navigation bar currently has icons placed at the center of a DIV, but I would like to fill up the entire DIV without any spaces left on the sides. The HTML code for the DIV containing the icons is as follows: <nav class="navbar navbar-expand navbar ...

Improving the form fields and Stimulus JS by eliminating the need to repeat the :data-action attribute for each individual field

I'm working with the following form <%= form_for( model, html: { :'data-controller' => 'enable-submit-button-if-fields-changed' } ) do |form| %> <%= form.text_field(:title, :'data-action&ap ...

Change the background color of numbers in an array using DOM manipulation in JavaScript

Can someone assist me with the following task: 1. Generate an array containing 10 numbers ranging from 0 to 360. 2. Display these numbers on the DOM within a chosen element. 3. Adjust the background color of each number based on its HUE value in (hue, sat ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...

I can't figure out why my SCSS isn't loading, even though I've added it to the webpack.mix.js file in my Laravel project that's set up with React.js

I'm facing a problem where my SCSS is not loading in the VideoBackground.js component of my Laravel project built with React.js, even though I have set it up correctly in the webpack.mix.js file. The file path for the videoBackground.scss file within ...

What steps can I take to ensure this barcode appears correctly on the screen?

Currently, I am utilizing a combination of CodeIgniter and Zend Framework to effortlessly generate a barcode: $this->load->library('zend'); $this->zend->load('Zend/Barcode'); $txt = $_POST['Info& ...