Fading and sliding: fade and slide
Besides show() and hide(), jQuery has two families of effects. Fading (fade) changes only opacity, and sliding (slide) changes only height. Both take a duration and a completion function, like hide().
Fading
<p id="message">Task added</p>
<button id="out">Hide</button>
<button id="in">Show</button>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#out').on('click', function () {
$('#message').fadeOut(400);
});
$('#in').on('click', function () {
$('#message').fadeIn(400);
});
</script>The message smoothly disappears and reappears. After fadeOut() the element gets display: none, and the space below it is freed.
Sliding
slideUp() collapses an element upwards, slideDown() expands it. slideToggle() picks the action itself, which is how expandable blocks are built:
<button id="more">More</button>
<div id="details" style="display: none">
<p>Tasks are saved in the browser and survive a page reload.</p>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#more').on('click', function () {
$('#details').slideToggle(300);
});
</script>Pressing the button expands the block of text, pressing again collapses it.
All effects
| Method | What it does |
|---|---|
fadeIn(), fadeOut() | Fades in or out |
fadeToggle() | Toggles opacity |
fadeTo(400, 0.5) | Fades to the given opacity without hiding |
slideDown(), slideUp() | Expands or collapses by height |
slideToggle() | Toggles collapsed state |
Deleting a task with a fade
The course example: the item fades out first and is removed only when the animation ends.
<ul id="tasks">
<li>Buy bread <button class="delete">Delete</button></li>
<li>Call Oleg <button class="delete">Delete</button></li>
</ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#tasks').on('click', '.delete', function () {
$(this).closest('li').fadeOut(300, function () {
$(this).remove();
});
});
</script>Inside the completion function this is the animated element, the li item.
Pauses and the queue
Effects on one element form a queue and run one after another. delay() adds a pause to the queue:
<p id="message" style="display: none">Saved</p>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
$('#message').fadeIn(200).delay(1500).fadeOut(400);
</script>The message appears, stays for a second and a half, and fades away: a typical toast notification.
The same in plain JavaScript
Without jQuery these effects are made with a CSS transition on opacity or max-height plus a class toggle, or with the element.animate() method.
Common mistake
Clicking a slideToggle() button quickly and watching the block keep sliding back and forth: every click added an effect to the queue. Stop the current effect with stop() before starting a new one:
// script.js
$('#details').stop().slideToggle(300);stop() interrupts the running animation, and the new one starts right from where the old one stopped.