Reputation: 655
I am doing something like this:
case: when i click on add link it should remove the class style on Div and Fadeout and then it should add a class and then fadein. But the problem is it removes the class, then adds class then performs fadeout and fadeIn. Why it is adding the class before fadeout?
here is my code
$(function(){
$('#noti1').click(function() {
$('#blue').removeClass( "ui-state-highlight").fadeOut(1000, mossawir);
function mossawir() {
setTimeout(function() {
$( "#effect" ).addClass( "newClass" );
}, 1500);
}
$('#blue').addClass("ui-state-error").fadeIn('slow');
});
});
I even tried a more simple way:
$(function() {
$('#noti1').click(function() {
$('#blue').removeClass( "ui-state-highlight").fadeOut('slow');
$('#blue').addClass("ui-state-error").fadeIn('slow');
});
});
Upvotes: 2
Views: 1241
Reputation: 339786
It's adding the class before you fade out because that's exactly what you told it to do.
jQuery's normal methods aren't processed as part of the animation queue, they're executed immediately.
You could try:
$('#blue')
.removeClass('ui-state-highlight')
.fadeOut(1000, mossawir)
.queue(function() {
$(this).addClass('ui-state-error')
$(this).dequeue();
})
.fadeIn('slow');
to insert the class change as part of the animation queue.
NB: this method preserves your existing completion callback (mossawir
) to add the newClass
effect once the .fadeOut
had completed. The other answers don't allow for that (yet).
Upvotes: 1
Reputation: 262919
That's because animation methods like fadeOut() and fadeIn() are asynchronous: they return immediately and perform their work later.
Since asynchronous methods return before they complete, they usually take a callback function argument that gets called when they do complete. In your case, you only need to run the fadeIn
animation when the fadeOut
effect completes, i.e. in its callback:
$("#noti1").click(function() {
$("#blue").removeClass("ui-state-highlight").fadeOut("slow", function() {
$(this).addClass("ui-state-error").fadeIn("slow");
});
});
Upvotes: 3