Advertisement

jQuery Succinctly: jQuery Effects

by
Student iconAre you a student? Get a yearly Tuts+ subscription for $45 →
This post is part of a series called jQuery Succinctly.
jQuery Succinctly: jQuery Plugins
jQuery Succinctly: jQuery and Ajax

Disable All jQuery Effect Methods

It is possible to disable all of the animating methods jQuery provides by simply setting the value of the off property to true.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px;">Try to animate me! </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script> (function($) {     
     jQuery.fx.off = true;     
     $('div').slideUp(); // Does not animate, hides immediately 
 })(jQuery); </script>
</body>
</html>

When off is set to true, all the effect methods will not animate and will instead be hidden and shown immediately using the CSS rules display:none and display:block. You can turn the animation back on by passing the off property a false value.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px;">
        Try to animate me!
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script> (function ($) {
     jQuery.fx.off = true;
     $('div').slideUp();
     jQuery.fx.off = false; // Turn animation back on    
     $('div').slideDown(); // It will now animate 
 })(jQuery); </script>
</body>
</html>

Grokking the stop() Animation Method

It is often necessary to stop an animation currently in progress before starting another. For example, when using the custom mouseenter and mouseleave events (or hover() method), you may unintentionally trigger an element that is already animating due to a previous mouseenter or mouseleave event. This causes a buildup of queued animations, which results in a sluggish interface. To avoid this, simply use the stop() method to stop the current animation before starting a new one.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px;">
        Hover over Me!
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('div').hover(function ()
      { $(this).stop().animate({ left: 75 }, 'fast'); },
        function () { $(this).stop().animate({ left: 20 }, 'fast'); });
  })(jQuery); </script>
</body>
</html>

Remove the stop() methods from the code and roll the mouse over the element several times to see the ghost animations occur. Continuously rolling over the element in the page will result in animation buildup, which is typically not the desired result.

Notes: Additionally, it is possible to not only stop the current animation in the queue for the select element but also the entire queue by passing the stop() method a parameter of true. This will effectively stop all queued animations, active and inactive.


Determining if an Element Is Animating Using :animated

The custom :animated selector filter can be used to select elements that are currently animating. Below, I use this custom selector filter to add text to an animating <div> element.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; color: white"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      function recursiveAnimate()
      { $('div').slideToggle('slow', recursiveAnimate); };
      recursiveAnimate(); $('div:animated').text('I am animating');
  })(jQuery); </script>
</body>
</html>

Using show(), hide(), and toggle(), Without Animation

Using the show(), hide(), and toggle() methods with a parameter will cause the elements being shown or hidden to animate by changing CSS properties: height, width, opacity, margin, padding. It is possible to skip animations for hiding and showing elements simply by not passing any parameters. This changes how these methods adjust the visibility of an element. Affected elements will simply appear or disappear without any animation by adjusting the CSS display property instead.

<!DOCTYPE html>
<html lang="en">
<head>
    <style type="text/css">
        div
        {
            height: 100px;
            width: 100px;
            background-color: red;
            color: white;
            margin: 5px;
        }
    </style>
</head>
<body>
    <div>Click Me (hide animation)</div>
    <div>Click Me (hide no animation)</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Hide with animation    
      $('div:first').click(function () { $(this).hide(1000) });
      // Hide no animation    
      $('div:last').click(function () { $(this).hide() });
  })(jQuery); </script>
</body>
</html>

Notes: The jQuery methods hide(), show(), toggle(), slideUp(), slideDown(), slideToggle(), when used on elements that have a CSS display value of inline, will be changed to display:block for the duration of the animation.


Grokking Sequential and Non-Sequential Animations

It is important to understand the difference between animations that happen simultaneously, and animations that occur in a sequential order over time. By default, when effect methods are chained, they are added to a queue, and each effect occurs one after another.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px; border: 1px solid #ff9933">
        Animate me!
    </div>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px; top: 100px; border: 1px solid #ff9933">
        Animate me!
    </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script> (function ($) {
     // Each effect is added to a queue and occurs sequentially    
     $('div:first').slideUp('slow').slideDown('slow').hide('slow');
     // Each method is added to a queue and occurs sequentially    
     $('div:last').animate({ width: '200px' }, 1000).animate({ borderLeftWidth: '10px' }, 1000);
 })(jQuery); </script>
</body>
</html>

Using the animate() method, you can set animations to occur non-sequentially or at the same time by passing all the CSS property changes to a single animate() method call. In the code below, the <div> will animate its width and border left width at the same time.

<!DOCTYPE html>
<html lang="en">
<body>
    <div style="height: 100px; width: 100px; background-color: red; position: absolute;
        left: 20px; border: 1px solid #ff9933">Animate me! </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script> (function($){     
     // Both width and borderLeftWidth properties will animate simultaneously    
     $('div').animate({ width: '200px', borderLeftWidth: '10px' }, 1000);
 })(jQuery); </script>
</body>
</html>

Animate() is the Base, Low-Level Abstraction

The animate() method is the base method that is used to construct all the pre-configured animations-e.g. hide(), slideDown(). It provides the ability to change (over time) the values of style properties.

Here is what you need to know when using this method.

  • Only properties that take numeric values are supported. In other words, you can't animate the value of, say, the backgroundColor property (at least not without a plugin). Also, properties that take more than one value like backgroundPosition can't be animated.
  • You can animate CSS properties by using em and % where applicable.
  • Relative animations can be specified using "+=" or "-=" in front of the property value. This would, for example, move an element positively or negatively relative to its current position.
  • If you specify an animation duration of 0, the animation will immediately set the elements to their end state.
  • As a shortcut, if a value of toggle is passed, an animation will simply reverse from where it is and animate to that end.
  • All CSS properties set via a single animate() method will animate at the same time.

Grokking the jQuery Fading Methods

Three concepts need to be called out when using the fadeIn(), fadeOut(), and fadeTo() methods.

  • Unlike other effect methods, fading methods only adjust the opacity of an element. It is assumed when using these effect methods that any element being faded already has a height and width.
  • Fading animations will fade elements from their current opacity.
  • Using the fadeOut() method will fade an element from its current opacity, and then once 100% faded, it will change the CSS display property of the element to "none".

Each of the aforementioned points is illustrated in the code below.

<!DOCTYPE html>
<html lang="en">
<body>
    <!-- Elements being faded should have a width and height -->
    <div style="height: 100px; width: 100px; background-color: red;"></div>
    <button>Fade the rest of the way</button>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
$('div').fadeTo('slow', 0.50);
      $('button').click(function () {
          // Fade from current opacity to zero,         
          // and then hide element via display:none        
          $('div').fadeOut('slow');
      });
  })(jQuery); </script>
</body>
</html>
Advertisement