Tuesday, 11 November 2008

JavaScript: Dynamically changing CSS properties of any DOM object

I was trying to create a web album the other day and played around with the gThumb image program. The program offers various templates that allow you to create web galleries with various different styles and it turned out that for me, the BestFit template was the best looking of them all.

The interesting part of the story is that when you create a web gallery based on the BestFit template, you also get a number of JavaScript files containing various programming goodies like the get and set property functions that I am displaying on this post. The copyright of these functions is Copyright (C) 2005-2006 Free Software Foundation, Inc., thus my thanks here go to Rennie deGraaf who provided both the template and the opportunity to get access to these functions.

So changing the width, height, or display mode of any DOM object found in your web page has never been so simple.

// set a property to a given value on an object
function setProperty ( obj, prop, val )
    if (obj.style.setProperty) // W3C
        obj.style.setProperty(prop, val, null);
    else // MSIE
        eval("obj.style." + prop + " = \"" + val + "\"");
// gets a style property for an object
function getProperty ( obj, prop )
    if (document.defaultView && 
        document.defaultView.getComputedStyle) {
        var val = document.defaultView.getComputedStyle( obj, 
        if (val)
            return val;
            return eval("document.defaultView.getComputedStyle(obj,null)." + prop);
    else if (window.getComputedStyle) // Konqueror
        return window.getComputedStyle(obj,null).getPropertyValue(prop);
    else if (obj.currentStyle)        // MSIE
        return eval('obj.currentStyle.' + prop);

No comments :