Wednesday, December 8, 2010

Add CSS style text to a DOM object in JavaScript

Today I am posting a function to programmatically add CSS text to an object using JavaScript.

Function

   var DeveloperCaster = {
            Css: function (id) {
                var styleTxt = '';
                if (arguments.length >= 2) {
                    for (var i = 0; i < arguments[1].length; i++) {
                        styleTxt += arguments[1][i] + ';';
                    }
                }
                //Check for IE
                if (window.attachEvent) {
                    $(id).style.cssText = styleTxt;
                } else {
                    $(id).setAttribute('style', styleTxt);
                }
            }
        }


Usage
The function request an object id and then you may pass as many CSS parameters as needed.


window.onload = function () {
        DeveloperCaster.Css('objectId', 'width:300px',
                                 'height:200px',
                                 'border:1px solid #333333');
    } 

No comments:

Post a Comment