Accessing CSS elements via JS quick how-to

This is a small quick reminder of how to access CSS style properties (and, as a bonus, how to detect Internet Explorer version from javascript and switch from PNG to GIFs to avoid not having transparency in IE versions less than 7).

Having this image:

<img id="HeaderTable" src="img/logobackground.png" />

We can have in a CSS file something like (dumb here, but just so you can notice how the property is called):

#HeaderTable
{

backgroundImage= 'url(img/logobackground.png)'
;
}

With this small script, we detect IE version and if less than 7 we change the image to it's GIF equivalent.

<script type="text/javascript" language="javascript">
var ieVer=/@cc_on function(){ switch(@_jscript_version){ case 1.0:return 3; case 3.0:return 4; case 5.0:return 5; case 5.1:return 5; case 5.5:return 5.5; case 5.6:return 6; case 5.7:return 7; }}()||@/0
;
if
(ieVer<=6
)
{
var image
;
image = $get('HeaderTable');
if
(image != null
)
image.style.backgroundImage
='url(img/logobackground.gif)'
;
}
</script>

Can you guess how to access properties? just with .style.xxxxxx, where xxxxxx is lowercase name with first letter of the second and consecutive words in capital, and no spaces or hyphens.
Another example: font-family equals fontFamily

Simple, but efficient!

Note #1:I know this JS will fail under Firefox and similar, but it was used inside a Messenger Activity Window so it will always be Internet Explorer ;)


Note #2: The $get() notation is because of using the fantastic Microsoft AJAX library :)

Comments?

Posted by Kartones on 2008-05-04