Example: Node Styling

This example shows how to style an element using Node.

Click me to change my color and show some style information.

Setting up the HTML

First we need some HTML to work with.

<div id="demo">
    <p>Click me to change my color and show some style information.</p>
</div>

Using Style Methods

In this example, we will set the node's color and compare the style and computedStyle values when our demo node is clicked.

var onClick = function(e) {
    var node = e.currentTarget;
    if (!node.one('dl')) { // only create the DL once
        node.setStyle('color', 'green');
        var styleColor = node.getStyle('color'),
            computedColor = node.getComputedStyle('color');

        node.append('<dl>' +
            '<dt>style.color</dt><dd>' + styleColor + '</dd>' +
            '<dt>computedStyle.color</dt><dd>' + computedColor + '</dd>' +
        '</dl>');
    }
};

The last step is to assign the click handler.

Y.one('#demo').on('click', onClick);

Complete Example Source

<div id="demo">
    <p>Click me to change my color and show some style information.</p>
</div>

<script type="text/javascript">
YUI().use('node', function(Y) {
    var onClick = function(e) {
        var node = e.currentTarget;
        if (!node.one('dl')) { // only create the DL once
            node.setStyle('color', 'green');
            var styleColor = node.getStyle('color'),
                computedColor = node.getComputedStyle('color');

            node.append('<dl>' +
                '<dt>style.color</dt><dd>' + styleColor + '</dd>' + 
                '<dt>computedStyle.color</dt><dd>' + computedColor + '</dd>' +
            '</dl>');
        }
    };

    Y.one('#demo').on('click', onClick);
});
</script>