What JavaScript Can Do for Your Pages - HTML 4

Adding scripts to your Web site is much like those makeover reality television shows that transform a house or a person’s appearance into something completely new and wonderful. So too with JavaScript. You can transform a plain and dull Web page into an interactive and dynamic Web extravaganza that will give your visitors joy and enjoyment for years to come. Okay, maybe we’re exaggerating just a little bit, but you get the point.

For example, if you visit Dummies.com (www.dummies.com) and click the red button next to the search box without entering a term to search on, the browser displays a nice warning box that reminds you to enter a search term before you actually search, as shown in Figure.

Figure : A script pops up a dialog box telling you what you did wrong

A script pops up a dialog box telling you what you did wrong

A short script verifies whether you’ve entered a search term before the engine runs the query:

  • If you enter a search term, you don’t see the warning.
  • If you don’t enter a search term, the script built into the page prompts the warning dialog box to appear.

This bit of scripting makes the page dynamic, which means that it adds programmatic functionality to your Web pages and allows them to respond to what users do on the page — for example, filling out a form or moving the mouse pointer over an image. When you add scripts to your page, the page interacts with users and changes its display or its behavior in response to what users do.

The page URL doesn’t change and another browser window doesn’t open when you try to search on nothing. The page responds to what you do without sending a request back to the Web server for new page. This is why the page is considered dynamic.

If you tried this trick without using a script (that is, without the dynamic functionality), the browser would send the empty search string back to the Web server. Then the server would return a separate warning page reminding the user to enter a search term. All the work would be done on the Web server instead of in the Web browser. This would be slower (because the request must first go to the server, and then the server must transmit the warning page back to your browser), and would feel much less fluid to the user. It’s much better to just click a button on the page and instantly have an alert pop up to help the user.

In the following sections, we showcase three common ways in which JavaScript can be used in your Web pages.

Don’t worry about the details of the JavaScript code in the following examples. Just focus on how JavaScript scripts can be pasted into your Web page and work alongside your HTML markup.

Arrange content dynamically
JavaScript can be used with CSS to change the look of the content on a page in response to a user action. Here is an example: Two authors share a Weblog, Backup Brain (www.backupbrain.com). One of the authors prefers small, sans-serif type, and the other one finds it easier to read larger, serif type. So the Weblog has buttons that change the look of the site to match each person’s preference. Of course, the site’s visitors can use the buttons to switch the look of the type, too, and the site remembers the visitor’s choice for future visits by setting a cookie, which is a small preference file written to the user’s computer. Figure shows the two looks for the page.

Figure : Clicking the “Change your font” buttons changes how the text displays.

Clicking the “Change your font” buttons changes how the text displays.

JavaScript and CSS can create this effect by switching between two style sheets:

  • The sans-serif style sheet, sansStyle.css
  • The serif style sheet, serifStyle.css

Listing shows the source code of an example page that contains this switching mechanism.

  • When a user clicks the Sm Sans button on the page, the styleSwitcher. js script referenced in the <head> element runs and switches the active style sheet to sansStyle.css.
  • When the user clicks the Lg Serif button, the same script switches to the serifStyle.css style sheet.

Listing : Style Switching

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Style Changer</title>
<link href=”simpleStyle.css” rel=”stylesheet” rev=”stylesheet” />
<link href=”sansStyle.css” rel=”stylesheet” rev=”stylesheet”
title=”default” />
<link href=”serifStyle.css” rel=”alternate stylesheet”
rev=”alternate stylesheet” title=”serif” />
<style type=”text/css” media=”all”>@import “complexStyle.css”;</style>
<script src=”styleSwitcher.js” language=”javascript1.5”
type=”text/javascript”></script>
</head>
<body>
<div class=”navBar”>
<br />Change your font:
<form action=”none”>
<input type=”button” class=”typeBtn” value=”Sm Sans”
onclick=”setActiveStylesheet(‘default’)” />
<input type=”button” class=”typeBtn2” value=”Lg Serif”
onclick=”setActiveStylesheet(‘serif’)” />
</form>
</div>

div class=”content” id=”headContent”>
<p>Replace this paragraph with your own content.</p>
</div>
</body>
</html>

Work with browser windows
JavaScript can tell your browser to open and close windows.

You’ve probably seen the annoying version of this trick: advertising pop-up windows that appear when you try to leave a site.

But this technology can be used for good as well as evil. For example, you can preview a set of big image files with small thumbnail versions. Clicking a thumbnail image can perform such actions as

  • Opening a window with a larger version of the image.
  • Opening a page with a text link that opens a window with an illustration of that text, as shown in Figure.

The code required to do this sort of pop-up window is fairly straightforward, as Listing shows.

Figure : When you click the link, a popup window appears with a picture in it.

When you click the link, a popup window appears with a picture in it

Listing : Pop-up Windows

Pop-up windows can backfire on you if you use them too much. Many Web sites use pop-up windows to deliver ads, so users are becoming desensitized (or hostile) to them and simply ignore them (or install software that prevents them). Before you add a pop-up window to your site, be sure it’s absolutely necessary.

Solicit and verify user input
A common use for JavaScript is to verify that users have filled out all the required fields in a form before the browser actually submits the form to the form-processing program on the Web server. Listing places a formchecking function, checkSubmit, in the <script> element of the HTML page and references it in the onsubmit attribute of the <form> element.
Listing : Form Validation

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Linking scripts to HTML pages</title>
<script type=”text/javascript” language=”javascript”>
function checkSubmit ( thisForm ) {
if ( thisForm.FirstName.value == ‘’ ) {
alert(‘Please enter your First Name.’);
return false;
}
if ( thisForm.LastName.value == ‘’ ) {
alert(‘Please enter your Last Name.’);
return false;
} return true;
}
</script> </head><body>
<form method=”POST” action=”/cgi-bin/form_processor.cgi”
onsubmit=”return checkSubmit(this);”>
<p>
First Name: <input type=”text” name=”FirstName” />
Last Name: <input type=”text” name=”LastName” />
<input type=”submit” />
</p>
</form>
</body>
</html>

This script performs one of two operations if either form field isn’t filled in when the user clicks the Submit button:

  • It instructs the browser to display a warning to let the user know he or she forgot to fill in a field.
  • It returns a value of false to the browser, which prevents the browser from actually submitting the form to the form-processing application.

If the fields are filled in correctly, the browser doesn’t display alerts and returns a value of true, which tells the browser that the form is ready to pass on to the Web server. Figure shows how the browser displays the alert if the first name field is empty.

Figure : A good use of JavaScript is to validate form data.

A good use of JavaScript is to validate form data.
Although this example only verifies whether users filled out the form fields, you can create more advanced scripts that check for specific data formats (such as @ signs in e-mail addresses and only numbers in phone number fields).

When you create forms that include required fields, we recommend that you always include JavaScript field validation to catch missing data before the script can even find its way back to the server. Visitors get frustrated when they take the time to fill out a form only to be told to click the Back button in their browsers to provide missing information. When you use JavaScript, the script catches any missing information before the form page disappears so users can quickly make changes and try to submit again.

But wait . . . there’s more!
You can do much more with JavaScript. The following list highlights several common uses of the scripting language:

  • Detect whether a user has a browser plug-in installed that handles multimedia content
  • Build slide shows of images
  • Automatically redirect the user to a different Web page
  • Add conditional logic to your page, so that if the user performs a certain action, other actions are triggered
  • Create, position, and scroll new browser windows
  • Create navigation bars and change the menus on those bars dynamically
  • Automatically put the current date and time on your page
  • Combine JavaScript and CSS to animate page elements

Figure : The Gmail interface is powered by JavaScript.

The Gmail interface is powered by JavaScript.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

HTML 4 Topics