Accessing CSS Styles


document.getElementById("para").style.fontWeight =      "strong"; 

JavaScript can set any CSS commands and is "almost" using the name of the CSS command as the JavaScript property. However, there is a problem: Some characters, like the dash, are not allowed within a JavaScript property. But many CSS commands like, for instance, font-weight, do have dashes in them. Therefore, the JavaScript language uses a lowerCamelCase syntax: Every component starts with an uppercase letter, but not the very first one. So the CSS command font-weight can be set using the fontWeight property.

All CSS commands may be accessed using the style property of every styleable HTML element on the page. There are two common ways to access these elements:

  • Using event handlers in the form of HTML attributes, and submitting a reference to the current element as the parameter: <p onmouseover="handlerFunction(this);" />.

  • Accessing the element using document.getElementById().

The following listing shows the latter approach. The <p> element is selected using document.getElementById(); then the font-weight CSS command is set:

Changing a CSS Command (style.html)

<script language="JavaScript"   type="text/javascript"> function makeBold() {   document.getElementById("para").style.fontWeight =     "bold";   window.setTimeout("makeLighter();", 1000); } function makeLighter() {   document.getElementById("para").style.fontWeight =      "lighter";   window.setTimeout("makeBold();", 1000); } window.onload = makeBold; </script> <p >CSS and JavaScript</p> 

Tip

When a Mozilla browser is used, the JavaScript console also shows an error when an invalid value for the chosen style will be applied, as Figure 4.1 shows. This is extremely convenient when you're debugging.


Figure 4.1. Mozilla browsers (here: Firefox) complain about invalid CSS values.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net