Practical Examples - HTML

The uses for JavaScript are potentially unlimited. The following sections highlight a few of the more popular uses.

Browser identification and conformance
Using JavaScript you can determine what browser is being used to access your content and adjust the features of your documents accordingly. For example, you wouldn’t want to use a JavaScript feature, such as window.focus(), with a browser that doesn’t support the function. If you are using DHTML and the Document Object Model (DOM), it helps to know what browser is being used so you can determine the correct DOM model to utilize.

Typically, you can find the details of the browser in the navigator.userAgent variable. For example, if someone is using Microsoft Internet Explorer version 6, this variable would contain something similar to the following:

Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;
.NET CLR 1.0.3705; .NET CLR 1.1.4322)

From the content of the variable, you can determine that the browser is Mozilla 4.0 compatible and, specifically, is MSIE 6.0. This variable contains a lot of information, much of it superfluous to our intent—just knowing the browser. Additional variables exist to help ferret out the information without having to parse the navigator .userAgent value. Some of these variables are listed.

Practical Examples

Using if/then statements, you can provide the appropriate code for various browsers, similar to the following:

browser=navigator.appName
if (browser.indexOf(“Microsoft”)!=-1)
{
// Browser is MSIE, insert browser
// browser specific code here
}
if (browser.indexOf(“Netscape”)!=-1)
{
// Browser is vintage Netscape, insert
// browser specific code here
}
if (browser.indexOf(“Mozilla”)!=-1)
{
// Browser is Mozilla, insert
// browser specific code here
}

However, this method is far from fool proof because the browser itself supplies this information—many browsers masquerade as other browsers and don’t report their full details. A better way to write code is to detect actual features instead of relying on the browser name to ascertain which features it supports.
You can tell if a function, method, or property exists by using an if statement. For example, to determine that window.focus is supported by the user’s browser you could use a construct similar to the following:

if (window.focus)
{
// window.focus() is supported, use it
}
else
{
// window.focus() is not supported,
// use alternate method
}

If you are using DHTML or otherwise making use of the DOM, you have probably noticed that different browsers implement the DOM differently. You can use the preceding method with document objects to determine the appropriate DOM model to use with code similar to the following:

if (document.getElementById) {
// access DOM via getElementById
}
else if (document.all) {
// access DOM via document.all
}
else if (document.layers) {
// access DOM via document.layers
}

Note that you can determine if a browser supports DHTML at all by checking for any of the DOM models:

if (document.getElementById || document.all
|| document.layers)
{
// browser can do DHTML
}

Tip:The Quirksmode Web site (www.quirksmode.org) is an excellent source of browser compliance, quirks, and solutions.

Last modification date
Using the lastModified property of the document object, you can place the timestamp of the current document file in your document’s text. For example, the following code will insert the date (in the default format: MM/DD/YYYY HH:MM:SS)

wherever the code is placed in the document:

<script>
document.write(document.lastModified);
</script>

Caution:The lastModified property is problematic when used with some browsers. Always test your code on target browsers before fully deploying it.

Rollover images
Using the DOM, JavaScript can dynamically change images in the current document. This technique is commonly used with graphical buttons—you create buttons that have a different look when the mouse passes over them and use the onMouseOver event to trigger a script to change the button accordingly.
For example, suppose you created the two buttons shown. The button on the left is to be displayed when the mouse is not over the button, and the one on the right displays when the mouse is over the button.

The document code to handle the rollover change is shown in the following listing:

Two buttons for rollover purposes-—

Two buttons for rollover purposes

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”>
<html>
<head>
<title>Rollover Sample</title>
<script type=“text/JavaScript”>
function btnHigh( btnName, hgh ) {
// Display correct button - hgh = 0 = normal button
// hgh = 1 = highlight button
var obtn = document.getElementById(btnName);
if (hgh) {
obtn.src = btnName + “Hgh.jpg”;
} else {
obtn.src = btnName + “Nrm.jpg”;
}
}
</script>
</head>
<body>
<img id=“btnHome” src=“btnHomeNrm.jpg”
border=“0”
onMouseOver=“JavaScript:btnHigh(‘btnHome’,1);”
onMouseOut=“JavaScript:btnHigh(‘btnHome’,0);”>
</body>
</html>

This code works by using one function called by the OnMouseOver and onMouseOut events of the <img> element. When a user puts the mouse over the image, the function is called with the root name of the button (btnHome) and the highlight variable (hgh) set to 1 (highlight). The function gets the button’s id via the name (note how the <img> element’s id is the same as the root name of the images) and sets the element’s src property to the highlighted image. This process is repeated when the user removes the mouse from the element, but the highlight variable (hgh) is set to 0 (do not highlight), and the function sets the element to the normal image. You can use the same function for an unlimited number of buttons as long as each uses a unique id and the same image file-naming conventions.

Tip :To actually make the button do something, add an onClick event to the <img> tag to call another function, or directly manipulate the document .location.href property, as in the following examples:

onClick=“JavaScript:dosomethingelse()”

and

onClick=“document.location.href=‘home.html’”

Caching images
When animating images on a page, it helps to have the images (and all their variants) already cached by the browser. This eliminates the lag caused by the server sending the image(s) to the browser and the resulting delay in the image being displayed. To cache images, you can use a function similar to the following JavaScript function:

function preloadimages() {
var pictures = new Array
// List all the images to preload here
(
“images/rdm1.gif”
,“images/rdm2.gif”
,“images/rdm3.gif”
,“images/rdm4.gif”
,“images/rdm5.gif”
,“images/rdm6.gif”
,“images/rdm7.gif”
,“images/rdm8.gif”
,“images/rdm9.gif”
);
// Load each image in array
for (i=0;i<preloadimages.arguments.length;i++) {
myimages[i]=new Image();
myimages[i].src=preloadimages.arguments[i];
}
}

This function creates a new image object for each entry in the pictures array, causing the browser to request the image from the server and cache it locally. Thereafter, any request for the image will be served from the browser’s cache instead of the server, eliminating display lag.

To use this function, replace the images/rdm... entries with the correct URLs of the images you want to preload, and call the function from an onLoad event within the document, as shown in the following example:

<body onLoad=“JavaScript:preloadimages();”>

Note that preloading images takes just about as long as displaying the images normally. As such, little can be gained by preloading static images in the current document. However, images on subsequent pages, images used in animations, or dynamic buttons (see the previous section) are all good candidates for preloading.

Form validation
Form validation is one of the purposes most used by JavaScript. Consider the simple form shown.

A simple form to request a quote for shipping products.

A simple form to request a quote for shipping products.

Although the form is simple, a few pieces of information should be verified before the data is accepted:

  • The quantity should be a number and be at least three.
  • The ZIP code should be a five-digit number.
  • The e-mail address should resemble a valid e-mail address (include an @ and a period).

Performing complex checks on the data—such as validating that the ZIP code is authentic, not just five random numbers—isn’t feasible using JavaScript. But the following document provides enough validity to weed out totally bogus data:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01//EN”>
<html>
<head>
<title></title>
<script type=“text/JavaScript”>
function req(myField, myLabel) {
// Check for non-blank field
var result = true;
if (myField.value == “”) {
alert(‘Please enter a value for the “’
+ myLabel +‘” field.’);
myField.focus();
result = false;
}
return result;
}
function grThan (myField, myLabel, num) {
// Check if field value > num
var result = true;
if (myField.value <= num) {
alert(‘Please enter a value for the “’
+ myLabel +‘” field, greater than ’
+ val + ‘.’);
myField.focus();
result = false;
}
return result;
}
function isInt (myField, myLabel) {
// Check if field is an integer
var result = true;
if (!req(myField, myLabel))
result = false;
if (result) {
var num = parseInt(myField.value,10);
if (isNaN(num)) {
alert(‘Please enter valid number in the “’
+ myLabel +‘” field.’);
myField.focus();
result = false;
}
}
return result;
}
function validEmail(myField, myLabel) {
// Check for “valid” email (not empty, has
// “@” sign and “.”)
var result = false;
if (req(myField, myLabel))
result = true;
if (result) {
var tempstr = new String(myField.value);
var aindex = tempstr.indexOf(“@”);
if (aindex > 0) {
var pindex = tempstr.indexOf(“.”,aindex);
if ((pindex > aindex+1) &&
(tempstr.length > pindex+1)) {
result = true;
} else {
result = false;
}
}
}
if (!result) {
alert(“Please enter a valid email address ”
+ “in the form: yourname@yourdomain.com”);
myField.focus();
}
return result;
}
function valform (myform) {
// Validate form fields as specified below
// Quantity > 2 (and integer)
if ( !grThan(myform.qty,“Quantity”,2) ||
!isInt(myform.qty,“Quantity”) ) {
return false;
}
// Valid Zipcode
if (!isInt(myform.zip,“Zipcode”)) {
return false;
}
// Valid email
if (!validEmail(myform.email,“Email”)) {
return false;
}
return true;
}
</script>
</head>
<body>
<h1>Order Request</h1>
<p>Please enter details below. We will reply to
your request within two business days.</p>
<form name=“orderform”
action=“http://www.synergy-ent.com/projects/pi.php”
method=“POST”
onSubmit=“return valform(document.orderform);”>
<p>
<table border=“0” cellpadding=“5”>
<tr><td>
Quantity desired:<br>
(minimum 3)
</td><td>
<input type=“text” name=“qty” value=“3”
size=“4”>
</td></tr>
<tr><td>
Zipcode for estimating<br>
shipping cost:
</td><td>
<input type=“text” name=“zip” value=“”
size=“5” maxlength=“5”>
</td></tr>
<tr><td>
Email address:
</td><td>
<input type=“text” name=“email” value=“”
size=“20” maxlength=“30”>
</td></tr>
<tr><td>
&nbsp;
</td><td>
<input type=“submit” value=“Submit”>
</td></tr>
</table>
</p>
</form>
</body>
</html>

This code works by using the onSubmit event with the <form> element. When the user clicks the Submit button, the event handler calls the specified function (valform) before actually submitting the form data to the specified handler. If the function returns true, the form data is submitted. If the function returns false, the form data is not submitted and the user is returned to the document. The valform function steps through a handful of smaller functions to validate parts of the form. The various functions return true if the data is valid, false if the data is invalid. If all functions return true, the main function returns true as well, allowing submission of the data. If any function returns false, the main function also returns false, and the data is not submitted.

Each validation function also displays an error message if invalid data is encountered, placing the user agent focus on the offending field.

Note:The functions used here are typical of functions used to validate most form data. However, each form is different and will probably require custom functions to validate its content—although you can use this example as a template, you should create tests specifically for your data.

A comprehensive collection of form validation scripts can be found in the archives of Netscape’s DevEdge site:

http://developer.netscape.com/docs/examples/javascript/ formval/overview.html

Although the code was written in 1997, it still contains a wealth of useful functions for form validation.

Specifying window size and location
By accessing the user agent’s properties you can manipulate some aspects of the user’s browser window. Table lists a handful of the useful properties available.

Specifying window size and location

Note:The resize methods resize the entire window of the user agent, which includes toolbars, status bars, and so on—not just the content. Several other methods and properties can be used to return information about the browser and set certain attributes, but most of them are hit or miss as far as browser compliance is concerned. You can find more information on the properties and methods at
DevGuru:

You can use the code in the following example to play with some of the browser window properties and methods:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<!-- Note the use of the transitional DTD above! -->
<html>
<head>
<title>Window Functions</title>
<script type=“text/JavaScript”>
function resetwindow() {
// Reset window to upper left of screen
// at a size of 500 x 400 pixels
window.resizeTo(500,400);
window.moveTo(0,0);
}
function sizeBy(x,y,smaller) {
// Increase or decrease (if smaller)
// size of window by x and y pixels
if (smaller) {
x *= -1;
y *= -1;
}
window.resizeBy(x,y);
}
function scrollreport() {
// Report position of both scrollbars
var hpos, vpos;
var hmsg, vmsg;
if (navigator.appName ==
“Microsoft Internet Explorer”) {
hpos = document.body.scrollLeft;
vpos = document.body.scrollTop;
} else {
hpos = window.pageXOffset;
vpos = window.pageYOffset;
}
hmsg = “Horz Scroll: ” + hpos;
vmsg = “Vert Scroll: ” + vpos;
alert(hmsg + “n” + vmsg);
}
</script>
</head>
<body onLoad=“resetwindow();”>
<div style=“width: 600px; height: 600px;”>
<form>
<p><input type=“button” value=“Reset”
accesskey=“R”
onClick=“resetwindow();”></p>
<p><input type=“button” value=“Larger”
accesskey=“L”
onClick=“sizeBy(50,50,0);”>
<input type=“button” value=“Smaller”
accesskey=“S”
onClick=“sizeBy(50,50,1);”></p>
<p><input type=“button” value=“ScrollBar Report”
accesskey=“B”
onClick=“scrollreport();”></p>
<p><input type=“button” value=“Close Me”
accesskey=“C”
onClick=“self.close();”></p>
</div>
</body>
</html>

Note:The <div> sets a specified size for the elements in the document body to help ensure that scrollbars will appear at smaller window sizes. Note that the accesskey attributes for the buttons allow you to access the buttons even if you can’t see them in the document window.

Frames and frameset control
You can also use JavaScript to help direct content to specific frames, if your document uses frames.The window.frames property can be used to access the frames currently active in the user agent window. You can access the frame properties using two methods, by name or by position in the frameset:

<!-- A frameset -->
<frameset rows=“25%,50%,25%”>
<frame name=“frame1” src=“banner.html” />
<frame name=“frame2” src=“content.html” />
<frame name=“frame3” src=“footer.html” />
</frameset>
// Access a frame (frame2) by name
window.frames[“frame2”].location=“home.html”
// Access a frame by position in frameset
// (first frame is 0, second frame is 1)
window.frames[1].location=“home.html”

Either of the two preceding JavaScript examples will replace the content of frame2 with that of the home.html document.

Tip:You can use the window.frames.length property to determine how many child frames are currently displayed in the active user agent window.

Using cookies
The Web is largely a stateless environment. The user agent requests a page and receives a response from the server. Typically, neither entity tracks the user’s state (beyond the client’s concept of Back and Forward through the cache). Enter cookies, a way to save information on the user’s machine that the user agent can later retrieve and use.

Note:Over the years, cookies have gotten a bad reputation. The technology is not at fault, but the use of it is. Several individuals and companies have used cookies to track user behavior and report the data for demographic, shopping, or simply spying purposes. The heart of the cookie technology is fairly benign and can be used for very useful purposes, such as remembering what messages you have read in a forum, favorite settings for sites, and so on. You can use the JavaScript document.cookie property to set and retrieve cookies. The following code shows examples of functions to set, retrieve, and delete cookies:

// setCookie
// Sets cookie specified by ‘name’ (and optionally
// ‘path’ and ‘domain’) to ‘value’.
// Cookie defaults to expire at end of session,
// but can be specified to expire ‘expires’
// number of milliseconds from now.
function setCookie(name, value, expires, path, domain) {
if (expires) {
if (expires != 0) {
var curDate = new Date();
var expDate = new Date(curDate.getTime() + expires);
}
}
var curCookie = name + “=” + escape(value) +
((expires) ? “; expires=” + expDate : “”) +
((path) ? “; path=” + path : “”) +
((domain) ? “; domain=” + domain : “”);
document.cookie = curCookie;
}
// getCookie
// Retrieves cookie value specified by ‘name’ (and
// optionally ‘path’ and ‘domain’).
// Returns cookie value or null if cookie is not found.
function getCookie(name) {
var dc = document.cookie;
var prefix = name + “=”;
var begin = dc.indexOf(“; ” + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
} else {
begin += 2;
}
var end = document.cookie.indexOf(“;”, begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin + prefix.length, end));
}
// delCookie
// Deletes cookie specified by ‘name’ (and
// optionally ‘path’ and ‘domain’) by setting
// expire to previous date.
function delCookie(name, path, domain) {
if (getCookie(name)) {
document.cookie = name + “=” +
((path) ? “; path=” + path : “”) +
((domain) ? “; domain=” + domain : “”) +
“; expires=Thu, 01-Jan-70 00:00:01 GMT”;
}
}

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

HTML Topics