Changing Style Classes On-the-Fly


Changing Style Classes On-the-Fly

In the preceding two examples, we changed individual style attributes. But what if you have dozens of style attributes you've set up in a style class?

It turns out that you can change the style class of an element on-the-fly in JavaScript. You might expect that you use a property named class for that to match the HTML CLASS attribute, but the word class is already reserved in JavaScript, so you use a property called className instead. Here's an example showing how that works. In this case, I'll change the style class of a <DIV> element from blue to red text when the mouse moves over the element:

(Listing 21-11.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Text Mouse Rollovers Using Style Classes          </TITLE>          <STYLE>              .red {color:red}              .blue {color:blue}          </STYLE>      </HEAD>      <BODY>              <H1>                  Text Mouse Rollovers Using Style Classes              </H1>  <DIV CLASS=blue ONMOUSEOVER="this.className='red'"   ONMOUSEOUT="this.className='blue'">   Change this text's color with the mouse!   </DIV>  </BODY>  </HTML> 

You can see the results in Figure 21.6.

Figure 21.6. Using dynamic style classes.

graphics/21fig06.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

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