YUI Library Home

Site Search (YDN & YUIBlog):

# YUI Library Examples: Dom Collection: Using setStyle

# Dom Collection: Using setStyle

Clicking the button will use Dom's `setStyle` method to set the opacity of the element.

View example in new window.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

## Using setStyle

`setStyle`, part of the YUI Dom Collection, makes it easy to set the style properties of an HTMLElement. One of the benefits of this method is that it provides normalized (and simpler) mechanism for setting opacity in Internet Explorer.

To illustrate the use of `setStyle`, we'll create a `<div>` called `foo`. When the button is clicked, the opacity of `foo` will be set to `0.5`.

Add some simple CSS rules and markup for the demo element:

<style type="text/css"> #foo { background-color:#00f; color:#fff; height:100px; width:100px; } </style> <div id="foo">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div> <button id="demo-run">run</button>

Now we will define the function that sets the opacity of `foo`. The first argument of the `setStyle` method is either the ID of an HTMLElement, or an actual HTMLElement object. The second argument is the style property being set, and the third is the value to be applied to the property.

<script type="text/javascript"> var fade = function() { YAHOO.util.Dom.setStyle('foo', 'opacity', 0.5); }; </script>

Next we will use the YUI Event Utility's `on` method to listen for clicks on the button.

<script type="text/javascript"> YAHOO.util.Event.on('demo-run', 'click', fade); </script>

This is a simple example of how to use the `YAHOO.util.Dom.setStyle` method. In addition to normalizing opacity, `setStyle` fixes other properties that vary across browsers (e.g. "float").

## 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: Logging and debugging is currently turned off for this example.

Reload with logging
and debugging enabled.

### Dom Collection Examples:

### More Dom Collection Resources:

- User's Guide (external)
- API Documentation
- Cheat Sheet PDF (external)

Copyright © 2010 Yahoo! Inc. All rights reserved.

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