Reputation: 3020
This is my HTML code
<div id="menu_status_item">
<span class="menu_status_bar"></span>
</div>
This is my CSS:
#menu_status_item
{
margin-top: 40px;
width: 100%;
}
.menu_status_bar
{
margin-left: 45px;
color: #fff;
}
And this is my jquery
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");
Basically i want the text "Success" inside the menu_status_bar to appear, do the animation, and disappear with the display: none.
If i use the display:none at the end, the text won't even show up. If i remove it, the animation works, but the text will remain there... if someone selects it, its horrible because the text will be highlighted.
Does any one know what could this be? or how can i achieve the same result but doing it differently?
Thanks.
Upvotes: 0
Views: 57
Reputation: 2118
Because of the asynchronous nature of JavaScript, the animate command starts the animation but it doesn't what for it to finish before executing the next line of code. You want to hide the text after it's done animating. jQuery provides the 'complete' callback for this:
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}, {
duration: 4000,
complete: function() {
$(".menu_status_bar").hide();
}
});
see: http://api.jquery.com/animate/
Upvotes: 0
Reputation: 42440
The "text doesn't even show up" because the display: none
is not waiting for the animation to finish. You need to use the animation's callback function to schedule things after the animation finishes.
$("#selector").animate({backgroundColor: colorCode}, 4000, function() {
// callback function
// only executes after animation is over
});
Upvotes: 2