Skip to content

Animation

The principle of implementing animations with JavaScript is quite simple: by modifying the CSS styles of a DOM element slightly (e.g., increasing its height and width by 10%) at fixed time intervals (like every 0.1 seconds), it appears as if an animation is occurring.

However, manually implementing animations in JavaScript requires writing complex code. If you want to encapsulate the animation effects in functions for reuse, there are even more considerations.

Using jQuery to implement animations simplifies the process drastically—often requiring just one line of code!

Let’s first look at a few built-in animation styles in jQuery:

show / hide

When you call show() and hide() without parameters, they display and hide DOM elements. However, if you pass a time parameter, it becomes an animation:

javascript
let div = $('#test-show-hide');
div.hide(3000); // Gradually disappears over 3 seconds

The time is in milliseconds, but you can also use string values like 'slow' or 'fast':

javascript
let div = $('#test-show-hide');
div.show('slow'); // Gradually shows over 0.6 seconds

The toggle() method determines whether to call show() or hide() based on the current state.

Effect demonstration:

  • hide('slow')
  • show('slow')
  • toggle('slow')

slideUp / slideDown

You may have noticed that show() and hide() expand or contract from the top left corner, whereas slideUp() and slideDown() do so vertically.

slideUp() hides a visible DOM element, similar to pulling down a curtain, while slideDown() is the opposite. The slideToggle() decides the next action based on the element's visibility:

javascript
let div = $('#test-slide');
div.slideUp(3000); // Gradually disappears upwards over 3 seconds

Effect demonstration:

  • slideUp('slow')
  • slideDown('slow')
  • slideToggle('slow')

fadeIn / fadeOut

fadeIn() and fadeOut() create fading effects by continuously adjusting the opacity property of the DOM element. The fadeToggle() decides the next action based on visibility:

javascript
let div = $('#test-fade');
div.fadeOut('slow'); // Fades out over 0.6 seconds

Effect demonstration:

  • fadeOut('slow')
  • fadeIn('slow')
  • fadeToggle('slow')

Custom Animation

If the above animations don’t meet your requirements, you can use animate(), which allows you to implement any animation effect. You need to pass the final CSS state of the DOM element and the duration; jQuery will continuously adjust the CSS until the desired values are reached:

javascript
let div = $('#test-animate');
div.animate({
    opacity: 0.25,
    width: '256px',
    height: '256px'
}, 3000); // CSS transitions to specified values over 3 seconds

You can also pass a callback function that executes when the animation completes:

javascript
let div = $('#test-animate');
div.animate({
    opacity: 0.25,
    width: '256px',
    height: '256px'
}, 3000, function () {
    console.log('Animation completed');
    // Reset to initial state:
    $(this).css('opacity', '1.0').css('width', '128px').css('height', '128px');
});

This callback function can also be applied to basic animations.

With animate(), you can create a variety of custom animation effects.

Chained Animations

jQuery's animation effects can be executed sequentially, and you can use the delay() method to pause between animations, allowing for more complex animations while keeping the code simple:

javascript
let div = $('#test-animates');
// Animation effects: slideDown - pause - enlarge - pause - shrink
div.slideDown(2000)
   .delay(1000)
   .animate({
       width: '256px',
       height: '256px'
   }, 2000)
   .delay(1000)
   .animate({
       width: '128px',
       height: '128px'
   }, 2000);

Since animations take time to execute, jQuery must continuously return new Promise objects to facilitate subsequent operations. Simply wrapping animations in a function is not sufficient.

Effect demonstration:

  • animate()

Why Some Animations Might Not Work

You may encounter cases where certain animations like slideUp() have no effect. This is because jQuery animations gradually change CSS values, like height from 100px to 0. However, many non-block elements do not respond to height changes, rendering the animation ineffective.

Additionally, jQuery does not support animations for background-color, and using animate() to set background-color will not work. In these cases, you can use CSS3 transitions to achieve animation effects.

Exercise

Showing an animation when deleting an item is better than directly calling remove(). Please add a fade-out animation effect when deleting a row from the table:

html
<table id="test-table">
    <tbody>
        <tr>
            <td>Name</td>
            <td>Email</td>
            <td>Address</td>
            <td>Status</td>
        </tr>
        <tr>
            <td>Bart Simpson</td>
            <td>bart.s@primary.school</td>
            <td>Springfield</td>
            <td>Active</td>
        </tr>
        <tr>
            <td>Michael Scofield</td>
            <td>m.scofield@escape.org</td>
            <td>Fox River</td>
            <td>Locked</td>
        </tr>
        <tr>
            <td>Optimus Prime</td>
            <td>prime@cybertron.org</td>
            <td>Cybertron</td>
            <td>Active</td>
        </tr>
        <tr>
            <td>Peter Parker</td>
            <td>spider@movie.org</td>
            <td>New York</td>
            <td>Active</td>
        </tr>
        <tr>
            <td>Thor Odinson</td>
            <td>thor@asgard.org</td>
            <td>Asgard</td>
            <td>Active</td>
        </tr>
    </tbody>
</table>
javascript
function deleteFirstTR() {
    let tr = $('#test-table>tbody>tr:visible').first();
    // TODO: Add fade-out animation
    tr.fadeOut(600, function() {
        $(this).remove(); // Remove after fading out
    });
}

deleteFirstTR();
Animation has loaded