CIT041J Index > Lecture Notes - Dynamic Styles

CIT041J Lecture Notes - Dynamic Styles

You already know how to use Cascading Style Sheets to add presentation to your structured XHTML. Now you will learn how to change the presentation under user control with JavaScript.


Up to now, you have given a name="" attribute to everything you want to control. For dynamic HTML, you will give tags an id="" attribute. These attribute values must begin with a letter and consist only of letters, digits, and underscores, and they must be unique. Consider the following paragraph with a span in it:

This is a paragraph, this is the span, and this is the rest of the paragraph.

<p>This is a paragraph,
<span id="span1">this is the span</span>,
and this is the rest of the paragraph.</p>
<form action="#">
    <input type="button" onclick="changeSpan()" value="Change Span"/>

Let us to change the style of the <span> so that it has a color of red, a background-color of light yellow, and a font-size of 18 point. Here is the code, with line numbers for reference:

1   function changeSpan( )
2   {
3       var spanObject = document.getElementById("span1");
5 = "red";
6 = "18pt";
7 = "#ffffcc";
8   }
Line 3
The document.getElementById() function returns a reference to the object with the id that you specify. In this case, we want the object with id="span1".
Line 5
This sets the color property of the style attribute of the spanObject to red.
Lines 6-7
In CSS, you would set font-size and background-color. However, since you can’t have a dash in a JavaScript variable name, the rule is to remove the dash and capitalize the next letter.

Older Browser Blues

If you are running older browsers, this won’t work, because the browser doesn’t support the getElementById() method. Rather than writing code to look at navigator.appName and navigator.appVersion, you should instead check to see if the capability exists.

function changeSpan( )
    if (document.getElementById)
        var spanObject = document.getElementById("span1");
    = "red"; = "18pt"; = "#ffffcc";
        window.status="Sorry, this feature not available.";

Important: the if statement does not use the parentheses! You don’t want to call the method; you just want to see if that method name exists in the document.