Home / DHTML & CSS / Getting global and external style sheet values in DHTML


 

CodingForums
Having trouble with scripting? Visit our help forum to get the answers you need.

Jump to...
-Free JavaScripts
-JS tutorials
-JS Reference
-DHTML/CSS

-Free applets
-Web Tutorials
-Link to Us!


Cross browser function for retrieving global/external CSS properties

Ok, time to combine all that we've learned thus far and create a cross browser function to getting and returning any global and external CSS property value. Some object detection is all that we need to top things off:

<script type="text/javascript">

function cascadedstyle(el, cssproperty, csspropertyNS){
if (el.currentStyle) //if IE5+
return el.currentStyle[cssproperty]
else if (window.getComputedStyle){ //if NS6+
var elstyle=window.getComputedStyle(el, "")
return elstyle.getPropertyValue(csspropertyNS)
}
}

</script>

To use this function, simply pass into it the element in question, plus both the hyphenated CSS property and unaltered property name (the later for NS6):

<head>
<style type="text/css">
#test{
width: 100px;
height: 80px;
background-color: yellow;
}
</style>
</head>

<body>
<div id="test">This is some text</div>

<script type="text/javascript">

var mydiv=document.getElementById("test")

function cascadedstyle(el, cssproperty, csspropertyNS){
if (el.currentStyle)
return el.currentStyle[cssproperty]
else if (window.getComputedStyle){
var elstyle=window.getComputedStyle(el, "")
return elstyle.getPropertyValue(csspropertyNS)
}
}

alert(cascadedstyle(mydiv, "backgroundColor", "background-color")) //alerts "yellow"
</script>
</body>

And there you have it! Now even your DHTML will approve of your using global and external style sheets!

-Tutorial introduction
-Getting global and external style sheet values in IE5+
-Getting global and external style sheet values in NS6+
-Cross browser function for retrieving global/external CSS properties

End of Tutorial

http://www.javascriptkit.com
Copyright © 1997-2005 JavaScript Kit. NO PART may be reproduced without author's permission.