Search code examples
jquerydelayfadeinaddclass

jquery + fadeOut element, addClass (while hidden), re-display element


I'm looking for some help on achieving the following:

when document ready ..

locate and hide a specified div from DOM, while it's faded / display is set to 'none', add a class of 'img2'. After class is appended to initial selector, fade div back in. (display:block)

How can I chain these following methods in order specified?

Currently, any 'addClass' method, is initiated as soon as DOM is ready instead of after chained events.

/*
select div, 
wait 2 secs., 
fade out for 1, 
add class 'img2' (which changes background-image property / style), 
re-display (display:block) selected element. (#bg-img).
*/
$('#bg-img').delay(2000).fadeOut(1000).addClass('img2');

Solution

  • jQuery.fadeOut supports a callback for code that should be applied after the effect has been completed:

    $('#bg-img').delay(2000).fadeOut(1000, function() {
      $(this).addClass('img2');
    });
    

    Update

    As @mdm quite rightly points out, you can pass a callback argument to all of the jQuery animation effects.