Fade in an element after another element has finished hiding

Promise objects in jQuery help you waiting for a specific action to start only after another action has completely finished. This comes in handy for example if you want to to fade in an element only after another one has completely faded out.

Let’s say we have two lines of text of which only the first one is displayed. When we click a button, the first line shall fade out and the second line fade in.

HTML:

<p id="element-1">Old text</p>
<p id="element-2">New text</p>

<button>Show new text</button>

 

CSS:

#element-2 {
    display: none;
}

 

If we want the new text line to appear in the same place as the old text line right away, we have to use a promise object. If we do not use one, the new text line will appear under the old text line before the old text line has finished fading out.

Bad solution without promise object:

$('button').on('click', function() {
    $('#element-1').fadeOut(1000);
    $('#element-2').fadeIn(500); 
});

 

Good solution:

Leave a Reply

Your email address will not be published. Required fields are marked *