HTML and CSS Reference
In-Depth Information
Problem Solving: Choosing Between Classes and Inline Styles
JavaScript allows styles to be changed in two ways. One approach is to modify the object's
appearance by setting or changing the object's inline style as in the following command,
which changes an object's font color:
document.getElementById(“heading1”).style.color = “red”;
Another approach is to keep all styles in an external style sheet marked with different class
names. A part of the CSS style sheet that changes the font color to red might look like
.redText {color: red}
allowing the programmer to change the font color by changing the class name as follows:
document.getElementById(“heading1”).className = “redText”;
There are several good reasons to use classes for this task rather than the style property.
First, using classes makes it easier to maintain consistent styles within a Web site because
all styles are confined to a style sheet rather than being spread across several style sheets
and JavaScript programs. Second, it is usually easier to use commands to modify a style in
a style sheet rather than in what might be a long and complex JavaScript program. Finally,
test speeds conducted by Peter-Paul Koch of QuirksMode.org have shown that browsers are
more responsive and apply style changes more quickly when you change the element class
rather than when you modify the style properties directly.
Still, situations exist where you wouldn't want to create different classes for every
change in an object's appearance, such as when that class value contains important struc-
tural information regarding the object's use or position in the document. For that reason,
most JavaScript programmers use a combination of different classes and inline styles to
modify the appearance of their documents.
Designing Styles for an Object Collection
You now have all of the tools you need to complete the user interface for the hanjie
puzzle. Rebecca wants you to add an onclick event handler to each data cell in the
puzzle. As a user repeatedly clicks a cell, the cell background color should change from
its current gold color to gray (indicating a marked cell), then to white (indicating an
empty cell), and finally back to gold again (indicating an unknown cell). You'll place the
commands to change the cell color in the changeBackground() function and then assign
that function to the onclick event for each data cell.
Search WWH ::




Custom Search