Animation with jQuery

Last updated .

Previous chapter

First chapter

Hiding elements with the hide method

The simplest form of animation imaginable is to hide and show stuff. The hide method can be used to hide elements and it does so by setting display:none in the element style. The method has the form jQuerySet.hide([/*object or string or number*/ durationOrOptions] [, /*string*/ easing] [, /*function*/ callback]) and returns a reference to the jQuery set it is called on. This simple example sets up two buttons to hide and show, respectively, a third element:

<button id="btnShow">Show</button> <button id="btnHide">Hide</button> <span id="spanA">Some text</span> <script> jQuery("#btnShow").click(function (event) { var span = jQuery("#spanA"); span.show(); console.log(span.attr("style")); } ); jQuery("#btnHide").click(function (event) { var span = jQuery("#spanA"); span.hide(); console.log(span.attr("style")); } ); </script>

The above example calls the hide method with no arguments, but the method is more versatile by using the parameters, as listed here:

The hide method works by progressively diminishing the width, height and opacity properties until the element becomes completely hidden by setting style.display equal to none.

Instead of specifying a duration, easing and callback, it is possible to pass settings in an options parameter, containing an object with these properties:

Showing elements with the show method

As the name suggests, the show method can be used to bring elements from a hidden state to a displayed state, optionally with an animation. The method has the form jQuerySet.show([/*object or string or number*/ durationOrOptions] [, /*string*/ easing] [, /*function*/ callback]) and returns a reference to the jQuery set it is called on. In other words, it is called with the same types of parameters as for the hide method shown above.

Showing or hiding elements with the toggle method

In some cases, you don't care if an element is currently displayed or hidden, you just want it to go from whatever state it is currently in to the other state. The toggle method brings hidden elements to a displayed state and vice versa. The method has the form jQuerySet.toggle([/*object or string or number*/ durationOrOptions] [, /*string*/ easing] [, /*function*/ callback]) and returns a reference to the jQuery set it is called on. In other words, it is called with the same types of parameters as for the hide method shown above.

Next chapter