CssProperty – the CSS property we will extract from the element, for example – “background-color”;
The function $style:
function $style(ElementId, CssProperty)
{
function $(stringId)
{
return document.getElementById(stringId);
}
if($(ElementId).currentStyle)
{
var convertToCamelCase = CssProperty.replace(/-(.)/g, function(m, l){return l.toUpperCase()});
return $(ElementId).currentStyle[convertToCamelCase];
}
else if (window.getComputedStyle)
{
var elementStyle = window.getComputedStyle($(ElementId), “”);
return elementStyle.getPropertyValue(CssProperty);
}
}
Example usage of the function:
1. Register the runtime routine of the $style in the <head>…</head>of your webpage, or as an external script.
2. The CSS for the example:
<style type=”text/css”>
#Div1
{
border: solid 1px red;
background: #00ff00;
color: #000;
font-family: “Trebuchet MS”, Arial, Verdana;
}
</style>
2. The HTML for the example:
<div id=”Div1″>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Cras purus pede, aliquam vel, eleifend in, mollis sit amet, ante.</div>
3. The JavaScript for the example:
<script type=”text/javascript”>
function getElementStyles()
{
var elBgColor = $style(“Div1”, “background-color”);
var elForeColor = $style(“Div1”, “color”);
var elFont = $style(“Div1”, “font-family”);
alert(‘”Div1″ style settings:nnbackground color: ‘ + elBgColor + ‘;n’ + ‘color: ‘ + elForeColor + ‘;n’ + ‘font-family: ‘ + elFont + ‘;’);
}
</script>
4. And finally, you need an event to fire function. It could be any DOM event. For this example I have used the click event of a button:
<input type=”button” onclick=”getElementStyles()” value=”Get Element Styles” />
This script is included in the latest version of Acid.JS – The AJAX Tools and Widgets Library as well.
© 2006 - 2023 Martin Ivanov