Apply CSS using JQuery at the start of an event and then revert it back at the end

Is there a way to notify users that the site is loading while a function with noticeable execution time is running? I have an associated change function which is connected to a drop down filter used for sorting through data on the page.

$("#job_group").change(function() {
        console.log("Change");
        $("#displayTable").css("opacity", "0.5"); // temporarily gray out the table during execution
        // Code that needs to run
        showResults();
        $("#displayTable").css("opacity", "1"); // revert back to normal once done
        console.log("Completed");
});

The console logs indicate that the desired behavior is being achieved, however, the initial css change seems to be ignored as it quickly reverts back even though the code execution takes time.

The expected sequence of events:

  • Execute Change Function
  • Set table opacity to opaque
  • Filter results
  • Restore table opacity to normal

EDIT

Show Results function retrieves the number of results

function showResults() {
        let count = 0;
        $(".jd-row").each(function() {
        if($(this).css("display") !== "none" && !$(this).hasClass("jd-row-expand")) {
            count++;
        }
    });
    $("#results").html(count + "");
}

Answer №1

It is important to note that the logic within the showResults() function operates synchronously, which means it can block the thread if not handled correctly. To prevent this, consider putting the function inside a timeout to allow JavaScript to update the DOM before the loop in the each() method runs. Additionally, remember to reset the opacity within the same timeout. Here's an example:

$("#job_group").change(function() {
  var $table = $("#displayTable").css("opacity", "0.5");
  setTimeout(function() {
    showResults();
    $table.css("opacity", "1");
  }, 50);     
});

Keep in mind that relying on long-running synchronous operations is not ideal. If possible, try to refactor the logic to be asynchronous. Alternatively, consider moving the filtering process to the server side and implementing AJAX for better performance.

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 best method for having tooltips hover over textboxes?

Hello there, Experts, I am still encountering some difficulties with the tooltips feature. The code snippet below functions properly in displaying the tooltips. However, a major issue arises where it causes the textbox to expand, resulting in misalignmen ...

Struggling to get troika-three-text installed via npm?

I'm having trouble integrating Troika with my three-js scene. While others seem to have no issue, I am struggling to call the module and encountering problems with references. It's frustrating because I can't seem to find any resources to he ...

module 'next/router' cannot be located or its associated type declarations are missing

Running into some issues with my NextJS application. An unusual error message is appearing, even though my code is functioning smoothly without any errors. import { useRouter } from 'next/router'; // Cannot find module 'next/router' or ...

What could be the reason my Virtual Mongoose categories aren't appearing?

Here is the description of my post model: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PostSchema = new Schema({ text: String, image: String, author: { type: Schema.Types.ObjectId, ref: 'user&ap ...

React - assigning a value to an input using JavaScript does not fire the 'onChange' event

In my React application with version 15.4.2, I am facing an issue where updating the value of a text input field using JavaScript does not trigger the associated onChange event listener. Despite the content being correctly updated, the handler is not being ...

Failure to prompt for authentication when accessing secure URLs via the $.ajax function

Whenever I work remotely, accessing URLs for our development servers always requires basic authentication. This means that every time a web page includes a script or link tag pointing to our development server, we encounter an authentication prompt. Recen ...

Adding a translucent overlay on top of a background image within a div, while keeping the text on top

Here is the current code that I am working with: <div class="square"> <div id="wrapper"> <h2>Text</h2> <h3>Text</h3> </div> </div> .square { padding: 10px; width: 150px; height ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

Adjusting jQuery tab content heights to maintain consistent height across tabs and prevent varying heights

I am currently working on a tabbed view that is very similar to the demo found at the following link: http://jsfiddle.net/syahrasi/us8uc/ $(document).ready(function() { $(".tabs-menu a").click(function(event) { event.preventDefault(); $(this).pare ...

Ajax request results in a 400 error code

Here is the structure of my Ajax call: function Submit() { var objectData = { email: $("#email").val(), firstName: $("#firstName").val(), lastName: $("#lastName").val(), loginMode: $("#login ...

Error message "mapStateToProps() in Connect(ModalRoot) must return an object literal. Received undefined." was thrown by the React-Redux container

I have been working on creating a Redux based Model/Dialog trigger inspired by Dan Abramov's solution to a similar problem on Stack Overflow. However, I encountered an error message saying "mapStateToProps() in Connect(ModalRoot) must return a plain ...

The Ionic Android app seems to constantly encounter dark mode display issues

I'm currently working on a small app that includes a menu, some chips, and a search bar. The issue I'm facing is that I've applied the MD theme to the entire app like this: @NgModule({ declarations: [AppComponent], entryComponents: [], ...

No elements present in TypeScript's empty set

Question for discussion: Can a type be designed in TypeScript to represent the concept of an empty set? I have experimented with defining one using union, disjoint union, intersection, and other methods... ...

Error 400 encountered when attempting to log in with React through Google on mobile devices

Currently, I am implementing the React Google Login package to handle user authentication on my website. Surprisingly, it functions perfectly on desktops; however, when tested on mobile devices, an annoying Error 400: redirect_uri_mismatch pops up. Despi ...

Tips on updating the initial value of a select box or placeholder?

Here is a select input: <select name="" id=""> <option disabled hidden selected value=""> default </option> <option value="2">2</option> <option value="3">3</option> <option value="3">3</option> ...

Seamless Integration of Hosted Fields by Braintree

I am currently struggling with setting up Braintree hosted fields on my registration form. Unfortunately, there are significant gaps between the fields which doesn't look appealing. Despite referring to the braintree documentation and guides, I find t ...

Error in JavaScript: A surprise anonymous System.register call occurred

Within Visual Studio 2015, there exists a TypeScript project featuring two distinct TypeScript files: foo.ts export class Foo { bar(): string { return "hello"; } } app.ts /// <reference path="foo.ts"/> import {Foo} from './f ...

Should the refresh button be displayed once the animation finishes?

Can anyone provide guidance on how to write jQuery code that will reveal a hidden button after an animation is finished? The button should also be able to refresh the animation for the user to watch again. Check out this fiddle: http://jsfiddle.net/rabela ...

Resolving cached CSS and JS files through the use of local storage

My customers frequently express frustration over not seeing the improvements I've made to my CSS or JS effects. The issue seems to be related to cached files. Perhaps this code snippet could provide a solution: $(document).ready(function(){ va ...

The CSS background fails to expand to the entire height of the element

I'm encountering an issue where an element with 100% height is extending beyond its boundaries when there are multiple blocks. For a demonstration, you can refer to this jsfiddle example: http://jsfiddle.net/yPqKa/ Any suggestions on how to resolve ...