What is causing this issue with my jQuery UI animation?

Below is the HTML code snippet:

<div id="menu_status_item">
    <span class="menu_status_bar"></span>
</div>

Here is the CSS code:

#menu_status_item
{
    margin-top: 40px;
    width: 100%;    
}

.menu_status_bar
{
    margin-left: 45px;  
    color: #fff;    
}

And the jQuery section:

var statusMessage = 'Success'
    var colorCode = '';
    var statusText = '';
    if(statusMessage.indexOf("Success") > -1) {
        colorCode = '#33CC33';
        statusText = 'Success';
    }else{
        colorCode = '#CC0000';
        statusText = 'Failure';
    }
    $(".menu_status_bar").css("display", "inline-table");
    $(".menu_status_bar").text(statusText);
    $("#menu_status_item").animate({backgroundColor: colorCode}, 4000);
    $("#menu_status_item").animate({backgroundColor: "#ffffff"});
    $(".menu_status_bar").css("display", "none");

I am trying to make the text "Success" appear inside menu_status_bar, do an animation, and then disappear by using display: none.

However, I am facing an issue where the text won't show up if I use display: none at the end. If I remove it, the animation works, but the text remains visible. This is a problem if someone tries to select the text as it gets highlighted.

Does anyone have any suggestions on how I can achieve the same result in a different way?

Thank you.

Answer №1

The reason why the "text doesn't appear" is because the CSS property display: none does not wait for the animation to complete. To solve this, you should utilize the callback function of the animation to schedule tasks after the animation finishes.

$("#selector").animate({backgroundColor: colorCode}, 4000, function() {
 // callback function
 // executes only after the animation is finished
});

Answer №2

Due to the asynchronous nature of JavaScript, when using the animate command, the animation starts but does not wait for it to finish before moving on to the next line of code. To hide the text after the animation is completed, jQuery offers a 'complete' callback:

let message = 'Operation successful'
let color = '';
let text = '';
if (message.includes("success")) {
    color = '#33CC33';
    text = 'Success';
} else {
    color = '#CC0000';
    text = 'Failure';
}
$(".status_bar").css("display", "inline-table");
$(".status_bar").text(text);
$("#status_item").animate({backgroundColor: color}, {
    duration: 4000,
    complete: function() {
        $(".status_bar").hide();
    }
});

For more information, visit: http://api.jquery.com/animate/

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

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

I encountered an issue with the mui TextField component in React where it would lose focus every time I typed a single character, after adding key props to

I'm encountering an issue with a dynamic component that includes a TextField. Whenever I add the key props to the parent div, the TextField loses focus after typing just one character. However, when I remove the key props, everything works as expected ...

How to Use AJAX to Read a Text File in JavaScript

Having trouble with AJAX! I have successfully set up a marquee on my website, but now I want it to dynamically fetch the text from a text file. The goal is to read the text from the file (which contains only one line) and assign it to a global variable nam ...

Deliver a JSON validation response to a modal in Laravel version 5.3

Recently, I delved into Laravel and attempted to utilize Laravel's built-in validation for my modal form. Surprisingly, everything was running smoothly without the validator. However, upon adding the validator code, an incessant 500 internal server e ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

What would be the ideal alternative if the Google Ajax API is unavailable, given that Google does not allow for local installation?

On my website, I include the following script: ... <script type="text/javascript" src="https://www.google.com/jsapi"></script> ... This particular script is from Google and is used to dynamically load other resources, such as the Google Chart ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Unable to See Success Notification on First Attempt

I am facing an issue with displaying a message when adding a new record. The first time I add a record, the message shows up correctly. However, if I try to add another record, the message does not appear even though the record is added successfully. Here ...

Can you explain the significance of "@c.us" in the context of whatsapp-web.js?

Are there any references or resources available for using "@c.us" that I can consult? Here is an example: client.on('ready', () => { console.log('Client is ready!'); // Your message. const text = "Hey John"; // Obt ...

Hide the border below the active tab

Could anyone assist me in removing the border below the selected tab? I've attempted multiple approaches without success. I experimented with adding a negative margin to the tab and creating a white border, but as the border I want to conceal is from ...

Encountering issues with the addEventListener function in a React application

Here's the scenario: I'm currently working on integrating a custom web component into a React application and I'm facing some challenges when it comes to handling events from this web component. It seems that the usual way of handling events ...

The filtering and sorting features of Ng-table do not seem to be working properly when dealing with grouped data

Currently, I am in the process of learning angular.js and have recently started using the ng-table directive. While I have successfully managed to group my data and display it using ng-table, I seem to be facing issues with sorting and filtering the data. ...

Solving regex issues within PHP

<div class="start">...</div> Is there a way to extract the content within <div class="start"> using PHP? I am looking for a regular expression solution that is capable of handling nested scenarios. ...

Is there a way to ensure that the text stays positioned behind the initial image even as the window size is adjusted

<html> <head> <title> Example </title> <style> img:hover {opacity : 0.3;} img {z-index : 1; height : 33%; width : 33%; } .first { position : absolute; top: 0%; left: 0%;} .second {position : absolute; top: 0%; left: 33%; ...

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

Currently seeking user coordinates for Vue implementation

I recently started using Vue and I'm working on capturing the lat/long of a user to be used in other functions within Vue. Currently, I am retrieving the coordinates and plan to utilize them in an API but for now, I am just logging them. Although I c ...

Assign a value to the cookie based on the input from the form

I recently asked a similar question, but it seems like I missed providing some context, which is why I couldn't get it to work. My goal is to set a cookie value of a form entry when clicking on it (using the carhartl jquery plugin), but nothing happen ...

Click event not triggering on dynamically inserted DIV using jQuery

After the page is rendered in the DOM using jquery, the following code is added: owldata = '<div class="item"><div class="ifl-removepic" ng-click="deleteDocument("'+e.target.result+'");"></div><img src="' + e.targe ...

When hovering over the bootstrap dropdown, the main dropdown remains a clickable link

How can I create a bootstrap dropdown menu that activates on hover, while still allowing the main button to link to a different page when clicked? Below is the HTML code: <div class="body-wrap"> <div class="container"> <nav class="navbar n ...

Using Bootstrap columns within a PHP while loop

Encountering an issue https://i.sstatic.net/twePb.png and the code in question is shown below: <div class="col-md-4 text-center animate-box"> <a href="work-single.html" class="work" style="background-image: url(images/port ...