YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: StyleSheet Utility: Animating multiple elements with StyleSheet

# StyleSheet Utility: Animating multiple elements with StyleSheet

In this example, we'll use the Animation Utility in concert with StyleSheet to apply style changes to a group of elements in concert over time.

View example in new window.

## Starting from the existing `<style>` node

This example includes a `<style>` element with some basic styling for the demo. We give the `<style>` element an id which we'll reference when we instantiate the StyleSheet instance.

<style id="demo_style" type="text/css"> .shrinky_dink { overflow: hidden; width: 450px; } .shrinky_dink div { display: inline; float: left; background: #000; margin: 1em; height: 150px; width: 150px; opacity: 1, filter: alpha(opacity=100); } </style> ... <div id="demo"> <p> <button type="button" id="demo_go">Start</button> </p> <div class="shrinky_dink"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> </div> </div>

## Use the `onTween` event from an Anim instance

We'll just be using a raw instance of `YAHOO.util.Anim` to leverage its timers and event structure. In particular, we'll subscribe to its `onTween` and `onComplete` custom events.

YAHOO.util.Event.onDOMReady(function () { // Default animation duration is 1 second var anim = new YAHOO.util.Anim(), // Modify the existing style node's stylesheet sheet = new YAHOO.util.StyleSheet('demo_style'), floor = Math.floor, go = YAHOO.util.Dom.get('demo_go'); // Update the StyleSheet on each frame of the animation anim.onTween.subscribe(function (type,data) { // How far along in the animation are we? var factor = data[0].duration / 1000, dim = (150 - floor(100 * factor)) + 'px', opacity = 1 - (0.8 * factor); sheet.set('.shrinky_dink div', { height : dim, width : dim, opacity: opacity // normalized across browsers }); }); anim.onComplete.subscribe(function () { go.disabled = false; }); YAHOO.util.Event.on(go, 'click', function () { go.disabled = true; anim.animate(); }); });

## Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

### YUI Logger Output:

Note: You are viewing this example in debug mode with logging enabled. This can significantly slow performance.

Reload with logging
and debugging disabled.

### StyleSheet Utility Examples:

### More StyleSheet Utility Resources:

- User's Guide (external)
- API Documentation

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings