<a href='javascript:showElement("div2")'>click me</a>
<div id='div2' style='display:none'>This will show up!</div>
<script type='text/javascript'>
function showElement(id)
var el = document.getElementById(id);
if (el){
el.style.display = 'block';
}
}
</script>
You go test it, it works fantastic. You develop the rest of your page and complete it. So to do things properly, you move most of the style attributes into a CSS file instead of doing inline style definitions. So now you have:
css file:
.toggleme {
display:none;
}
page file:
<div id='div2' class='toggleme'>This will show up!</div>
You go back and test your page, but it doesn't work any more! No error, but the div doesn't show up either. What gives?
It turns out that most browsers handle the .style attribute of an element as meaning the attribute value directly from the html itself, instead of the cascaded value. IE uses .currentStyle and .runtimeStyle to renote the read/write properties for cascaded styles, while Firefox/Opera/etc uses the DOM standard of document.defaultView.getComputedStyle(). But we want something we can call that will just set the silly style regardless of browser and regardless of where the style is actually declared.
I wrote an open source framework for doing a fair amount of client-side manipulation that is browser independent. I call this Interactive Website Framework -- you can check it out at IWF on sourceforge. But for our needs, we really only need a single function (which I modified slightly to eliminate calls to other functions in the framework):
function iwfStyle(id, styleName, newStyle){
var el = document.getElementById(id);
if (!el) { return false; }
var ret = '';
if (typeof(newStyle) != 'undefined'){
// assigning new style
if (el.runtimeStyle){
ret = el.runtimeStyle[styleName] = newStyle;
} else {
ret = el.style[styleName] = newStyle;
}
} else if (el.currentStyle) {
// reading IE style
ret = el.currentStyle[styleName];
} else {
// reading DOM style
try {
var cs = document.defaultView.getComputedStyle(el,null);
ret = cs.getPropertyValue(styleName);
} catch(e) {
}
}
return ret;
}
Now if we change our showElement function to simply call iwfStyle, we're set:
<script type='text/javascript'>
function showElement(id)
iwfStyle(id, 'display', 'block');
}
</script>
So now the call will work regardless of browser or where the style is defined. Check out the full framework on sourceforge. It includes a client-side Xml parser, an Ajax abstraction layer, and some rudimentary gui enhancements, like animating elements, docking elements, drag-n-drop, etc.