Sams Teach Yourself JavaScript in 24 Hours Free Open Book

Sams Teach Yourself JavaScript in 24 Hours

Previous Page
Next Page

Style Sheet Switching with JavaScript

Suppose you want to offer your visitors a choice of different ways of viewing your sitefor example, a choice of large or small fonts, or different background colors. Although you can use the style properties of elements within a page to make these changes individually, it would take a lot of code to change a page between drastically different styles.

One alternative is to create two or more completely separate style sheets, and use JavaScript to switch between them. This allows the user to have a large amount of control over the site's appearance without using a large and complex script.

Creating the HTML Document

First, you can create a basic HTML document for the style-switching example. This document will include a <script> tag for the script you'll create later, as well as links to two different style sheets. The HTML document for this example is shown in Listing 23.4.

Listing 23.4. The HTML Document for the Style-Switching Example

<html>
<head>
<title>Style Sheet Example</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<link rel="stylesheet" type="text/css" href="style2.css" disabled>
<script language="javascript" type="text/javascript"
   src="styleswitch.js">
</script>
</head>
<body>
<h1>multiple-choice styles</h1>
<p>This is a standard paragraph of text. Its font, margins,
colors, justification, and other attributes depend on the style
sheet you select. This paragraph includes some text in
<b>bold</b> and <i>italics</i>.
</p>
<p>You can select one of three styles for this document:
</p>
<ul>
<li><a href="#" onclick="Style(0,true);">Style sheet # 1</a></li>
<li><a href="#" onclick="Style(1,true);">Style sheet # 2</a></li>
<li><a href="#" onclick="Style(0,false);">No style sheet</a></li>
</ul>
<p>These links call a short JavaScript function that enables one
of this document's two linked external style sheets. You can edit
the style sheets to style this document in two different ways,
without changing any HTML.</p>
</body>
</html>

Although most of the document is just sample text to show off the styles of the different style sheets, it has several important components to make this technique work:

  • The <script> tag uses the src attribute to include a script, styleswitch.js.

  • There are two <link> tags to attach two external style sheets, style1.css and style2.css. The second tag includes the disabled attribute, so the document will be styled using only style1.css by default.

  • The three links within the <li> list items have event handlers that call the Style() function to switch styles.

By the Way

Some browsers don't correctly support the disabled attribute in HTML. The script you create later will use JavaScript to disable the second style sheet by default to ensure that only one style sheet is used, regardless of the browser.


Save the HTML document in a folder. You'll be adding two style sheets and a script file to the folder to complete the example. If you load the document into a browser before creating the style sheets, it will be displayed without styles. Figure 23.2 shows how the document looks with no styles applied.

Figure 23.2. The style-switching example displayed without styles.


Creating the First Style Sheet

Next, you can create the first of the two style sheets. Listing 23.5 shows the complete style sheet style1.css.

Listing 23.5. The First Style Sheet for the Style-Switching Example (style1.css)

body {
   font-family: Arial, Helvetica, sans-serif;
   font-size: 12pt;
}
P {
   margin-left: 10%;
   margin-right: 10%;
   text-align: justify;
   text-indent: 3%;
}
B { color: red; }
I { color: DarkViolet; }
H1 {
   font-size: 300%;
   text-align: center;
   text-transform: capitalize;
}
UL {
   margin-left: 20%;
   margin-right: 20%;
}
LI { margin-top: 10px;}

Save this style sheet as style1.css in the same folder as the HTML document. This style sheet assigns some basic styles to the body, and to specific tags: <p>, <h1>, and so on. Because this is the default style sheet, it will be used if you load the HTML document now. Figure 23.3 shows the document as styled by this style sheet.

Figure 23.3. The style-switching example using the first style sheet.


Creating the Second Style Sheet

The second style sheet, style2.css, uses some more dramatic styles and is unlikely to be suited to all viewers. This sheet is disabled by default. Listing 23.6 shows the second style sheet.

Listing 23.6. The Second Style Sheet for the Style-Switching Example (style2.css)

body {
   font-family: Times, "Times New Roman", sans-serif;
   font-size: 14pt;
}
P {
   margin-left: 20%;
   margin-right: 20%;
   text-align: left;
   text-indent: 0%;
}
B {
   color: black;
   background-color: aqua;
}
I { color: red;}
H1 {
   font-size: 200%;
   text-align: right;
   text-transform: uppercase;
}
UL {
   margin-left: 30%;
   margin-right: 30%;
   background-color: yellow;
}
LI { margin-top: 20px;}

Save this style sheet as style2.css in the same folder as the HTML document.

Creating the Script

You can use JavaScript to enable or disable style sheets. The <link> elements that you used to attach the two style sheets to the HTML document are objects in the DOM, and you can manipulate them using DOM methods. In this example, you will use the getElementsByTagName() method to find all of the <link> elements, and then enable one and disable the other. Listing 23.7 shows the complete JavaScript file.

Listing 23.7. The JavaScript File for the Style-Switching Example (styleswitch.js)

function Style(n,enable) {
  if (!document.getElementsByTagName) return;
  links = document.getElementsByTagName("link");
  links[n].disabled=!enable;
  links[1-n].disabled=true;
}
Style(0,true);

This script defines the Style() function, which accepts two parameters. The first, n, specifies the style sheet to activate. The second parameter, enable, specifies whether to enable the new style sheet (true) or to disable all style sheets (false). This feature is used by the No Style Sheet link.

Did you Know?

This example uses getElementsByTagName, but you could also assign an id attribute to each <link> tag and then use document.getElementById to find the object for each one individually.


The script enables (or disables, depending on the parameter) the chosen style sheet, and always disables the other sheet. The last line of the script calls the Style() function to select the first style sheet, just in case the browser doesn't support the disabled attribute.

To try the example, make sure you have all four files in the same folder: The HTML document, the two style sheets (style1.css and style2.css), and the script file (styleswitch.js). Load the HTML document into a browser and try clicking the links to change styles. Figure 23.4 shows the document after the second style sheet has been selected.

Figure 23.4. The style-switching example with the second style sheet selected.


Try It Yourself

Creating a Dynamic Form

In Hour 11, "Getting Data with Forms," you learned how JavaScript can work with data from HTML forms, and change form elements. Using the W3C DOM, you can take this one step further, creating a script that can add elements to a form or show or hide sections of a form.

Creating the HTML Document

Listing 23.8 shows the HTML document for this example, which defines an order form. The form will have two dynamic features: first, the Ship To address fields aren't shown unless they're needed, and second, a button enables you to add additional item fields to the form.

Listing 23.8. The HTML Document for the Dynamic Form Example

<html>
<head>
<title>Dynamic Order Form</title>
<script language="JavaScript" type="text/javascript"
   src="dform.js">
</script>
</head>
<body>
<h1>Order Form</h1>
<hr>
<form name="form1">
<b>Bill to:</b><br>
<b>Name:</b> <input type="text" name="customer" size="20"><br>
<b>Address 1:</b> <input type="text" name="addr1" size="20"><br>
<b>Address 2:</b> <input type="text" name="addr2" size="20"><br>
<b>City:</b> <input type="text" name="city" size="15">
<b>State:</b> <input type="text" name="state" size="4">
<b>Zip:</b> <input type="text" name="zip" size="9">
<hr>
<b>Ship to:</b><br>
<input type="radio" name="shipopt" value="same" checked
 onClick="Show(0);">
<b>Same Address</b>
<input type="radio" name="shipopt" value="other" onClick="Show(1);">
<b>Other Address</b>
<div ID="shipto" style="display: none;">
<br>
<b>Name:</b> <input type="text" name="shipname" size="20"><br>
<b>Address 1:</b> <input type="text" name="shipaddr1" size="20"><br>
<b>Address 2:</b> <input type="text" name="shipaddr2" size="20"><br>
<b>City:</b> <input type="text" name="shipcity" size="15">
<b>State:</b> <input type="text" name="shipstate" size="4">
<b>Zip:</b> <input type="text" name="shipzip" size="9">
</div>
<hr>
<div ID="items">
<b>Qty:</b>
<input type="text" name="qty1" size="3">
<b>Item:</b>
<input type="text" name="item1" size="45">
<br>
<input type="button" value="Add an Item"
onClick="AddItem();" ID="add">
</div>
<hr>
<input type="submit" value="Continue...">
</form>
</body>
</html>

Save this HTML document in a folder. If you load it into a browser, you'll see the form's default appearance, but the dynamic features won't work yet. Figure 23.5 shows the default look of the form.

Figure 23.5. The dynamic form before the script is added.


Adding the Script

The script for this example will include two functions: AddItem(), for adding items to the form, and Show(), for showing or hiding the ship-to address. Listing 23.9 shows the script file.

Listing 23.9. The JavaScript File for the Dynamic Form Example

// global variable
var items=1;
function AddItem() {
  if (!document.getElementById) return;
  // Add an item to the form
  div=document.getElementById("items");
  button=document.getElementById("add");
  items++;
  newitem="<b>Qty: </b>";
  newitem+="<input type=\"text\" name=\"qty" + items;
  newitem+="\" size=\"3\"> ";
  newitem+="<b>Item: </b>";
  newitem+="<input type=\"text\" name=\"item" + items;
  newitem+="\" size=\"45\"><br>";
  newnode=document.createElement("span");
  newnode.innerHTML=newitem;
  div.insertBefore(newnode,button);
}
function Show(a) {
  if (!document.getElementById) return;
  //Hide or show ship-to address
  obj=document.getElementById("shipto");
  if (a) obj.style.display="block";
    else obj.style.display="none";
}

Here's a breakdown of how this script works:

  • The first line defines a global variable, items, to keep track of the number of items. This is used to assign a unique name attribute to each <input> tag as they are added.

  • The AddItem() function adds additional Quantity and Item fields to the form using the insertBefore() DOM method.

  • The Show() function uses the style.display property to either show or hide the section with the id value shipto.

To try the script, save it as dform.js (or download the files from this book's website) and load the HTML document into a browser. Figure 23.6 shows the document with two additional item fields added and the ship-to address displayed.

Figure 23.6. The dynamic form in action.



Previous Page
Next Page
Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Y]


     Main Menu
Sams Teach Yourself JavaScript in 24 Hours
Table of Contents
Copyright
About the Author
Acknowledgments
Part I: Introducing the Concept of Web scripting and the JavaScript Language
Part II: Learning JavaScript Basics
Part III: Learning More About the DOM
Part IV: Working with Advanced JavaScript Features
Part V: Building Multimedia Applications with JavaScript
Part VI: Creating Complex Scripts
Hour 21. Building JavaScript Drop-Down Menus
Hour 22. Creating a JavaScript Game
Hour 23. Creating JavaScript Applications
Creating a Scrolling Window
Style Sheet Switching with JavaScript
Summary
Q&A
Quiz Questions
Quiz Answers
Exercises
Hour 24. Your Future with JavaScript
Part VII: Appendixes
Index


More Books
PHP Hacks
Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
The Koran (Holy Qur'an)
Macromedia Flash 8 Bible
Search Engine Optimization for Dummies
YouTube Traffic
PHP 5 for Dummies
Harry Potter and The Chamber of Secrets
Harry Potter and the Sorcerer's Stone
The Pilgrim's Progress
Wireless Hacks
Flash Hacks. 100 Industrial-Strength Tips & Tools
PayPal Hacks. 100 Industrial-Strength Tips and Tools
Amazon Hacks
Pdf Hacks
The Da Vinci Code
Google Hacks
The Holy Bible
Windows XP For Dummies
Harry Potter and the Half-Blood Prince
Seo Book
Upgrading and Repairing Networks
Macromedia Dreamweaver 8 UNLEASHED
Windows XP Annoyances
Windows XP Hacks
Microsoft Windows XP Power Toolkit
Teach Yourself MS Office In 24Hours
iPod & iTunes Missing Manual
PC Hacks 100 Industrial-Strength Tips and Tools
PC Overclocking, Optimization, and Tuning - 2th Edition
PC Hardware In A Nutshell 3rd Edition
PC Hardware in a Nutshell, 2nd Edition
Upgrading and Repairing PCs
Google for Dummies
MySQL Cookbook
Teach Yourself Macromedia Flash 8 In 24 Hours
PHP CookBook
Sams Teach Yourself JavaScript in 24 Hours
PHP5 Manual
Free Games Paper Airplanes
500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele