Older browsers do not have the ability to execute the scripts you place in your HTML code. When an older browser encounters a script, errors can occur that can annoy your readers and keep them from coming back to your page. To avoid this, you can put the HTML comment tags to work.
A comment can be included in your HTML code by beginning the text with the tag <! -- and ending it with -- > . You can put any kind of explanatory text between those two tags, and it will not be executed by any browser. However, browsers that understand the <SCRIPT> tag ignore HTML comment tags placed within the script. Putting HTML comment tags around your script will result in older browsers treating the text as if it were a non-executable comment, while browsers that understand your script will execute it, and ignore the comment tags. Here's how to set it up using JScript:
<SCRIPT LANGUAGE = "JScript"> <!-- Your JScript code here // -- >
Note that you need to proceed the comment end tag -- > with the JScript comment directive //, so JScript does not try to execute it.
ZD Journal's Microsoft Web Builder journal
The style attribute text-decoration can be used to add an underline, overline, or line-through to the text on your Web page. This can be specified using either style sheets or on the fly in script. The text-decoration value none removes any text-decoration that has been added to your text. Make note of the following, however, related to the text-decoration attribute:
1. In addition to the text-decoration values listed above, the WC3 recommendation includes a blink property that is not supported in IE 4.
2. Web page designers will sometimes use the text-decoration attribute to remove the lines under the links on their pages. For example, the following style sheet for the ANCHOR tag removes all lines under links:
<STYLE> A {text-decoration:none} </STYLE>
But removing the lines under links can be confusing for your readers since the protocol has always been to underline links; therefore, using text-decoration in this way is not generally advised.
Microsoft Web Builder
This tip is for IE 4.x and Netscape Navigator 3.x and up.
Often you want to include a sound file or a ShockWave movie to your Web page. These files are usually large and take a while to download. Your visitor may have a slower modem connection and may not want to wait and download the sound file or the animation. You can offer the visitor a choice by creating the link to the sound or animation file with JavaScript and asking the visitor before downloading. For example,
<A HREF="MyBigSound.wav" onClick="return window.confirm('Play Sound?');">
Click here to play MyBigSound.wav
</A>
Which will look like:
Click here to play MyBigSound.wav
Now if the visitor clicks on the link, JavaScript will display a confirmation window and let the visitor decide whether to proceed with playing the file. If the visitor clicks on the OK button, the sound file will be downloaded.
Microsoft Web Builder
Avoid putting double quotes inside of double quotes in your HTML code. You may not get a compiler error, but your script just won't work. Instead, substitute single quotes for any inner sets of double quotes, as in:
Link.innerHTML = "<a href = 'http://www.myplace.com/mypage.htm'> The Greatest Site on the Web </a>";
ZD Journals' Microsoft Web Builder journal
When using the element property innerHTLM to change the text of an element, make sure that you don't put hard carriage returns inside of the text string. Doing so will cause an "Unterminated string error." For example, the following code won't work:
myObj.innerText = "The innerText property sets or retrieves the text between the start and end tags of the current element. This read-write property can be any valid string.";
If you do want to include breaks in your script to make your page more readable, one solution is to use the JScript concatenation symbol to concatenate separate strings into one, as in:
myObj.innerText = "The innerText property sets or retrieves the" + " text between the start and end tags of the" + " current element." + " This read-write property can be any valid + " string.";
VBScript's concatenation symbol & works the same way. For both languages, just make sure that you add spaces between string segments, where necessary, since that won't be done automatically.
ZD Journals' Microsoft Web Builder journal
The most common way for a script function to be called is by having an element trap a event, which in turn calls the function, as in:
<DIV id = "myelement" onclick = "myfunction()"> Click here </DIV>
But what if you want a function to perform some task as soon as the page loads, without any user input? In that case, you can use the onload event, placing it in the BODY element of your page, as in:
<BODY onload = "myfunction()">
The function will be called immediately after the page loads, and no user input is required.
Microsoft Web Builder
Microsoft's IE4 supports the ability to change just about any CSS1 style attribute dynamically. To access an element's style, use the style object property that corresponds to the style attribute. For example, to change the font-weight of a <P> element:
<P id = p1> This is my paragraph
your script would include the statement:
document.all.p1.style.fontWeight = "bold";
Don't know the name of the style property for the style attribute you want to change? The conversion is easy. Starting with the style attribute name, capitalize the first letter of any word after a hyphen, remove the hyphens, and you've got that attribute's style property. For example, the style property for the attribute background-color is backgroundColor and the style property for border-top-width is borderTopWidth.
You should note that although Microsoft allows for dynamically changing the style object in a script block, Navigator does not.
ZD Journals' Microsoft Web Builder journal
Want to add a new in-line style sheet to an element on the fly? First get the original text using the element's innerText property, and then put it back into the element, with new tags, using the innerHTML property. Here's how:
oldtext = document.all.myelement.innerText; document.all.myelement.innerHTML = "<SPAN style='color:green; font-style:italic' >" + oldtext + "</SPAN>";
Pay particular attention to the quotation marks (both single and double) to be sure that the code works correctly.
Microsoft Web Builder
Netscape and Internet Explorer have different color palettes, so an 8-bit color that you choose using one browser may look completely different when displayed in another. To be sure that your color images look similar across browsers, confine your color choices to the 216 colors that are displayed similarly by both browswers. Here's how:
An 8-bit color is represented by a hex value made up of 6 hex numbers. The first two numbers represent the amount of red, the middle two the amount of green, and the last two the amount of blue (hence, the name, RGB value). If you confine your colors to any combination where red, green and blue are represented by the hex numbers 00, 33, 66, 99, CC, or FF, your colors will be within the cross-browser color range. This gives you 6 possible values for red, for green, and for blue, or 6x6x6 color combinations, which equals 216 color values.
ZD Journal's Microsoft Web Builder journal
If you want to compare the values in two different textboxes, and you don't want case to be a factor in whether or not the values are equivalent, you can convert the strings in both text boxes to one case or the other before you compare them. The String methods toLowerCase and toUpperCase make this very easy. They convert strings to all lowercase or to all uppercase, respectively. Here's an example:
var string1 = document.all.inputbox1.value;
var string2 = document.all.inputbox2.value;
if (string1.toLowerCase() == string2.toLowerCase())
alert("Strings are equivalent.");
The toLowerCase method converts both string1 and string2 to lowercase before the two strings are compared. Note that the strings themselves are not permanently changed; to keep the lowercase version of the strings, you would have to assign the results of the toLowerCase method to a variable, as in:
var lowerstring = string1.toLowerCase();
ZD Journals' Microsoft Web Builder journal
When you trap a keyboard event with any of the keyboard event handlers (onKeyUp, onKeyDown, or onKeyPress), the event object's keyCode property contains the character value of the key that triggered the event. However, the value in keyCode is a character code (Unicode in Internet Explorer and ASCII in Netscape Navigator), not an alphanumeric character. To do the conversion, you can use the JScript String method fromCharCode. The JScript statement below is an example of how it's done:
var charCode = String.fromCharCode(e.keyCode);
The keyCode property of e, the event that was trapped by the event handler, is sent to the String method fromCharCode, which converts the character code representation of the character to an alphanumeric character and assigns it to the variable charCode.
Microsoft Web Builder
If your page is heavy with text, try creating columns of text to make your page more visually appealing. All you need to do is create table cells (using the TD element) without creating rows. The code below arranges text into three columns, by putting the text within each <TD> tag in a separate column.
<HTML>
<HEAD>
<TITLE>New Page</TITLE>
<STYLE>
TD {vertical-align:top}
</STYLE>
<BODY>
<TABLE cols = 3 cellspacing = 2>
<COLGROUP span = 3>
<COL width = "30%">
<COL width = "30%">
<COL width = "30%">
</COLGROUP>
<TD>Your text here...</TD>
<TD>Your text here...</TD>
<TD>Your text here...</TD>
</TABLE>
</BODY>
</HTML>
Using the style attribute vertical-align:top is critical so that all three columns are aligned at the top of the page. Of course, feel free to play with the column widths and the cell spacing between columns.
Microsoft Web Builder
This tip is for IE 3.x and up, and NN 4.x and up.
When you use horizontal rules in your page, by default you get a 3D line. However, if you prefer, you can add attributes to the <HR> tag to create a solid line with no 3D look. For example, the following code creates a horizontal line to match the width of the page with a 3D effect:
<HR WIDTH=50%>
Like this:
To change the look, you can use:
<HR WIDTH=50% COLOR="blue" NOSHADE>
which creates a solid blue line to match the width of the page--with no 3D effect.
Like this:
Microsoft Web Builder
You can load any number of different files into a frame at run time using the frame's location object. As you would when building any project using frames, first build a file that defines your frame. For our example, we've defined a frame called myframe. The code below would then go in a separate file.
In the BODY of our code, we've placed a list of files from which the user can choose. When a user clicks on the file name he wants to load, the name of the file is passed as a parameter to the function. The function appends the ".htm" extension to the name, and assigns the complete name to the location object of the frame myframe, which loads the appropriate file into that frame.
<HTML>
<HEAD>
<TITLE> History topics </TITLE>
<SCRIPT>
function loadfile(whatfile) {
parent.myframe.location = whatfile + ".htm";
}
</SCRIPT>
</HEAD>
<BODY>
<DIV onclick = "loadfile('file1')" > Load file 1</DIV>
<DIV onclick = "loadfile('file2')" > Load file 2</DIV>
<DIV onclick = "loadfile('file3')" > Load file 3</DIV>
</BODY>
</HTML>
Microsoft Web Builder
This seems to be a little known fact. You can log into an FTP site via a Web browser by typing the following in your address bar.
ftp://username:password@site_adress
and if the site is on a different port other than 21, like 2121 specify afterwards like so:
ftp://username:password@site_adress:2121
Andy Campos
VBScript's random number generator, Rnd, only generates random numbers between 0 and 1. If you need numbers in a different range, use the following formula:
Int ((UpperBound - LowerBound + 1) * Rnd + LowerBound)
For example, if you want random numbers in the range of 0 to 10, your script would look like this:
randNum = Int ((10 - 0 + 1) * Rnd + 0)
Microsoft Web Builder
The information search engines will use to rank your site should all be contained within the site itself. Text, titles, descriptions, and keywords are important to consider when designing your site.
First, you'll want to make sure that the HTML text in your site includes references to the key words for your site topic. For example, if you're responsible for a site that focuses on online sales of vintage musical instruments, you'll want to mention vintage guitars, vintage drums, and online sales in your text. You should also give your keywords prominent placement on the page. Mentioning them in page headings and in the first few paragraphs will get more attention from the search engines than if this information is buried deep within the page. Be aware, also, that search engines focus on HTML text, not graphics. If your keywords are contained within graphics rather than page text, your site may not receive the rank it deserves.
An outdated bit of advice held that you should include "invisible" keywords in your Web pages. This is accomplished by using a solid color background, leaving blank space at the end of the page, and entering in your keywords in the same color as the background. This strategy proposed that the more often your keywords appeared on the page, the greater relevance ranking search engines would give to the page. Search engines have begun to wise-up to this trick, so it's best not to waste your time with it.
ZD Tips
In a previous tip, we recommended that you avoid placing hard returns within your strings. But what if you want your JavaScript code to write out a new line after a string? Use the backslash character "\n" to do just that. Here's an example, where newname is the name of a TEXTAREA you've placed on your page:
document.all.newname.value = "Washington" + "\n" + "George"
Since "\n" translates to a new line, this code will place:
Washington George
in your TEXTAREA.
There are other useful backslash characters that you might also find handy when you want to add certain characters to your strings. They are:
\" Double quote \' Single quote \\ Backslash \b Backspace \t Tab \g Form feed
So, if we change our code slightly to:
document.all.newname.value = "Washington" + "\n" + "\t" + "George"
we get:
Washington
George
in our TEXTAREA. Note that the backslash characters "\' " and "\"" also solve the problem of including single quotes and double quotes inside your strings, so that the code
document.all.newname.value = "Washington" + "\n" + "\t" + "\"" + "George" + "\""
creates
Washington
"George"
in our TEXTAREA.
Microsoft Web Builder
The code below gets the SELELCT OPTION that the user has selected (from the SELECT element's selectedIndex property) and uses that value to determine the correct branch in a case statement. Depending on the OPTION selected, the user is automatically taken to the URL for that OPTION.
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript" TYPE="text/javascript">
<!-- Begin hide script
function jmpMS(site) {
switch (site) {
case 0: return
break;
case 1: window.location.href = "http://www.fastguide.com"
break;
case 2: window.location.href = "http://www.yahoo.com"
break;
}
}
// End hide -->
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME = "selector">
<SELECT NAME="titles" SIZE="1" onChange = "jmpMS(this.selectedIndex)">
<OPTION>Jump to...</OPTION>
<OPTION>Fastguide</OPTION>
<OPTION>Yahoo</OPTION>
</SELECT>
</FORM>
</BODY>
</HTML>
Jennifer Hardy
You can use HTML 4.0's new <MAP> and <AREA> tags, along with the USEMAP attribute, to create client-side image maps. When combined with CSS positoning, these new features make creating an image map quick, easy and efficient. Here's how:
Place an image on your page using the CSS positioning attribute position:absolute and specifying the image's height and width. Include the USEMAP attribute to indicate the name of your image map, as illustrated below:
<IMG ID="myimage" SRC="myimage.jpg" STYLE="position:absolute;top:0cm;left:0cm" height="200" width="200" USEMAP=#map1>
The # indicates that the image map is found on the current page.
Now, create the image map. The MAP element consists of a name with which we can refer to it, and a series of <AREA> tags that define areas of the image that we want to use to trap events. Specifying the coordinates of the shape (rect, circle, poly) of each AREA is easy since you know the absolute coordinates of the image. Here's an image map that divides the image into four equal quadrants:
<MAP name = "map1"> <AREA SHAPE=rect COORDS="0,0,100,100" onclick = "dothis(0);"> <AREA SHAPE=rect COORDS="100,0,200,100" onclick = "dothis(1);"> <AREA SHAPE=rect COORDS="0,100,100,200" onclick = "dothis(2);"> <AREA SHAPE=rect COORDS="100,100,200,200" onclick = "dothis(3);"> </MAP>
When the user clicks on an AREA of the image, the onclick event calls the dothis(num) function with the correct value.
ZD Journals' Microsoft Web Builder journal
If you want to process a dollar amount that a user has entered into a text box (add it to a total, for example) the first thing you need to do is strip off the dollar sign, if there is one. Fortunately, there are several String methods that can help.
The charAt method extracts a single character from a string at the position passed as a parameter. You can use charAt to detect if you have a dollar sign in the first position within your string, as in:
var dollars = document.all.mytextbox.value;
var dollarsign = dollars.charAt(0);
if (dollarsign == "$" )
alert("You've got money");
Notice that the first position in a string is 0, not 1.
Then you can use a combination of the substring method and the length property to strip the dollar amount from the dollar sign. The length property returns the length of the string, and the substring method returns a string of characters given a starting and ending position. Your code would look like this:
var dollaramt = dollars.substring(1,dollars.length);
For example, if the variable dollars contained the string $43.50, dollaramt would now contain the string 43.50.
Microsoft Web Builder
You can easily use one script for a variety of different Web pages by placing your JavaScript code in a separate file. Create the file in a text editor, and name it using a .js extension. Then, in your HTML code, assign that file to the src attribute of a <SCRIPT> tag. For example, if you've got your script in a file called "validate.js", place a <SCRIPT> tag in your Web page document like this:
<SCRIPT language="JavaScript" src="validate.js"></SCRIPT>
Of course, you can have more than one <SCRIPT> tag within a Web page document. If you place generic functions within a .js file that you assign as a src to one <SCRIPT> tag, you can have a second <SCRIPT> block in your page that contains function calls to the functions within the .js file. This way, you can have several different Web pages calling the generic functions in the .js file, but passing the functions data that is specific to each page.
ZD Tips
This tip is for Internet Explorer 3.x and up and Netscape Navigator 4.x.
While Style Sheets are great for screen presentation, you must practice caution when defining font sizes in pixels, if your site visitors frequently print out content from your site. You may define font sizes in "points" instead. By nature "pixels" are relevant to the output devices resolution, while points (pt) are device-independent measurements. For example, consider the following lines of code:
<style>
P {font-size: 72px}
</style>
On a printer with a 75dpi resolution, 72px is around 1 inch, at 150dpi -- less than 1/2 inch, at 300dpi -- less than 1/4 inch, and at 600dpi -- less than 1/8 inch. To remedy this problem, use
<style>
P {font-size: 72pt}
</style>
Your printed font size will be 1 inch in all resolutions we described above.
Microsoft Web Builder
The inline frame element uses the tags <IFRAME> </IFRAME> to create a frame window you can embed within your Web page. Instead of specifying the rows and columns of a frameset, each inline frame has a width and a height, which can be specified in inches or in pixels. The inline frame also supports the marginHeight, marginWidth, frameborder, and scrolling attributes, as well as target and align. Here's an example of how an inline frame might be used:
<HTML> <HEAD> </HEAD> <BODY> <H1 align=center> My Links </H1> <IFRAME id = myiframe SRC="favorites.html" WIDTH="580" HEIGHT="280"> </IFRAME> <P> </BODY> </HTML>
The IFRAME's SRC property is assigned any page that you want loaded into the inline frame. Better yet, you can change the source dynamically using a script. Here's how:
First, place some buttons in the BODY code of your page that trap a click event.
<INPUT type = button value = "Favorite links" onclick = newframe(0)> <INPUT type = button value = "Links to family" onclick = newframe(1)> <INPUT type = button value = "Links to friends" onclick = newframe(2)>
Next, add a script between the <HEAD> and </HEAD> tags:
<SCRIPT>
function newframe (num) {
switch (num) {
case 0:
document.all.myiframe.src = "favorites.html";
break;
case 1:
document.all.myiframe.src = "family.html";
break;
case 2:
document.all.myiframe.src = "friends.html";
break;
}
}
</SCRIPT>
One word of warning: Loading someone else's page directly into a frame (or an inline frame) on your page is considered at very least a discourtesy, and may in fact violate that page's copyright laws. Note also that the inline frame element is currently only supported by Microsoft's Internet Explorer 4.0 and higher.
Steve Excell
IE 4 provides a variety of visual filters that can be used to apply different visual effects to elements on your Web pages. Filters are applied to HTML elements using the filter style attribute, and can have an effect on elements that define a rectangular space within the browser window (i.e., buttons, images, div and span blocks, etc.). The element must either be positioned on the page, or have a defined width.
One of IE 4's visual filters is the Alpha filter, which can change the transparency level of an element, making it appear faded. And one common use of the Alpha filter is to fade out a button, giving the impression that the button has been disabled. To create this effect as the result of a user's action, start by creating the element that you want to appear disabled with a statement like:
<INPUT type="button" value="Click me" id=dimbutton style="position:absolute; top:40; left:20; filter:Alpha(enabled=0)">
We've given this button the id "dimbutton." Note that the Alpha filter has been included in the inline style sheet for dimbutton, but that the filter's enabled property is set to 0, so it has not yet been applied.
Next, create the element that will trap the user action. How about another button:
<INPUT type="button" style="position:absolute; top:40; left:220" value="Disable that other button!" onclick = "disableIt()" >
Clicking on the Disable that other button! button calls the disableIt function, which looks like this:
function disableIt() {
dimbutton.filters.item(0).enabled = 1
dimbutton.filters.item(0).opacity = 25
}
The disableIt function enables dimbutton's Alpha filter (the first item in the filters collection), and sets the opacity of the filter to 25 (where 100 is fully opaque), making the button appear faded, and therefore disabled.
Microsoft Web Builder
The IE 4 children collection allows you to process all of the direct descendants of a particular element. In our example, we're using it to add up all of the numbers in a UL list. We've given the list the id mylist. Notice that, as in all IE 4 collections, we can get the number of items in the collection using the length property.
<HTML>
<HEAD>
<SCRIPT language = "JScript">
function additems() {
var sum = 0
//Get the number of items in the unordered list
var numlist = document.all.mylist.children.length
//For each item on the list
for (i = 0; i < numlist; i++) {
//Get an item and convert it to a number
listitem = document.all.mylist.children(i)
num = parseInt(listitem.innerText)
//Add it to the sum
sum = sum + num
}
}
</SCRIPT>
</HEAD>
<BODY>
<UL id = mylist>
<LI> 12 </LI>
<LI> 17 </LI>
<LI> 23 </LI>
</UL>
<INPUT type = button value = Process list onclick = additems()>
</BODY>
</HTML>
ZD Journal's Microsoft Web Builder
You can process all the data in an HTML table using two IE collections: the rows collection and the cells collection. Both are collections of the TABLE object. Suppose, for example, you want to calculate an average for the data in each row of a table. Besides the table holding the data (we've created one with an id of temptable), you'll need a for loop (we'll use JScript) and a place to store the averages (we'll use an array). Here's the code:
<HTML>
<HEAD>
<SCRIPT language = "JScript">
function calc_avg() {
//Number of tables rows
var numrows = 4
//Number of table columns
var numcols = 3
//Array to hold averages for each row
var AvgPerRow = new Array(4)
//Get a reference to the table
mytable = document.all.temptable
//For each row in the table
for (i = 0; i < numrows; i++) {
var sum = 0
//Go through each cell in the row
for (j = 0; j < numcols; j++) {
num = parseFloat(mytable.rows(i).cells(j).innerText)
sum = sum + num
}
//Calculate the average for the row
AvgPerRow[i] = sum/numcols
}
}
</SCRIPT>
</HEAD>
<BODY>
<TABLE id = "temptable" rules = all >
<TR><TD> 30 <TD> 30 <TD> 40 </TR>
<TR><TD> 40 <TD> 40 <TD> 50 </TR>
<TR><TD> 65 <TD> 69 <TD> 75 </TR>
<TR><TD> 71 <TD> 73 <TD> 78 </TR></TABLE>
<BR>
<INPUT TYPE = BUTTON VALUE = "Get averages"
style = "width:150" onclick = "calc_avg()"></INPUT><BR>
</BODY>
</HTML>
ZD Journal
This tip is for IE 3.x and up and Netscape Navigator 3.x and up.
Just like alphanumeric characters, you can also use a variety of special characters in JavaScript strings. These include carriage returns, tabs, and other non-printable characters that are essential to your text formatting. To use any of these characters, you'll need to include a backslash (\) followed by the character. Here is a list of special characters you can use:
\a: Alert (bell) produces a bell sound
\b: Backspace character. Moves the cursor back one character.
\f: Form-feed character. Indicates a new page on the printer.
\n: New line. Indicates a new line of text.
\r: Carriage return.
\t: Tab character. Moves the cursor to the next tab position.
You can include the special character directly in a string, like this:
document.write("R Computers \n is the best \n computer company.");
JavaScript will display this text in three separate lines. Like this:
R Computers
is the best
computer company.
Microsoft Web Builder
This tip is for Internet Explorer 3.x and up and Netscape Navigator 3.x and up.
If your Web site contains a series of documents, you can use JavaScript to create BACK and FORWARD buttons for easy navigation. To create such navigational buttons, use JavaScript's History object, like this:
<html> <body> <form> <input type="button" value="< Back" onClick="history.back();"><br> <input type="button" value="Forward >" onClick="history.forward();"> </form> </body> </html>
Microsoft Web Builder
Although JavaScript does not have a mathematical operator that results in the integer part of a division operation (called integral division, or Div in some languages), you can use the Math object's floor() method to create that result, as long as the values you are working with are positive. The Math object's floor() method returns the next integer less than or equal to the value it is passed. For example:
var result = Math.floor(5/3) //result = 1
The result is the equivalent of having the decimal part (or remainder) removed after the division operation has taken place, which is exactly what an integral division operation would do.
ZD Tips
The JavaScript eval method can convert a string to an executable JavaScript statement or expression. This includes converting strings to arithmetic expressions, assignment statements, or object references. For example, the string "2 + 2" is just a string; but eval("2 + 2") results in 4.
The most common use of the eval method is for converting strings to their equivalent object references. This can be very handy when you want to process multiple elements of a particular type. To make it easy, identify your elements by appending consecutive numbers to one name; for example, give the elements IDs like obj0, obj1, obj2, etc. You can then use the eval method to reference those elements in a simple loop. Take a look at the following script:
<SCRIPT>
function chgcolor() {
for (i = 0; i <= 3; i++) {
myobj = eval("obj" + i)
myobj.style.color = "red"
}
}
</SCRIPT>
The eval method will change each occurrence of the string ("obj0", "obj1", etc.) to its respective object reference, allowing you to change the properties of all of the elements at one time.
Note, by the way, that the use of the style property as we've done here is restricted to IE4 or higher. Note also that if IE supports a collection of the type of objects you want to process, looping through the collection would probably be preferable to the approach we take here.
ZD Journal
In the HTML 3.2 specification, there was no way for an author to associate text with an intrinsic control such as a radio button or text box. Unlike an ``A'' tag, which has an accompanying </A> tag and encloses text, the <INPUT> tag does not have an </INPUT> tag. Therefore, screen readers have a difficult time finding exactly what text to use to describe the control to the user. HTML 4.0 introduces the LABEL tag, which allows the author to associate text with another HTML element. This is particularly useful for associating text with intrinsic controls. Whenever an intrinsic control is used on a page, a LABEL tag containing its associated text should accompany it. Doing so provides an additional benefit: clicking the label toggles the value of the associated intrinsic control. To associate a LABEL tag with a radio button, use the following HTML syntax:
<FORM> <INPUT TYPE=radio ID=FirstButton NAME=radio1> <LABEL FOR=FirstButton>I'm the text for the first radio button</LABEL><BR> <INPUT TYPE=radio ID=SecondButton NAME=radio1> <LABEL FOR=SecondButton>I'm the text for the second radio button</LABEL> </FORM>
Microsoft Web Builder
page breaks when printing Web pages
To use this technique, include the MEDIA="print" attribute in a style block, as shown:
<HTML>
<HEAD>
<STYLE MEDIA="print">
<!--
page { page-break-before: always }
//-->
</STYLE>
</HEAD>
Then add the CLASS="page" attribute to the element you want to appear on a new page. For example,
<BODY> <H1>I'm on the first page</H1> <P CLASS = "page"> </P> <H2>This begins the second page</H2> <H2 CLASS = "page">This is on the third page! </H2> </BODY> </HTML>
Note that these styles are invoked only when the pages are printed, and they are supported only by IE 4.x and above.
Dave Crowley
Try using the OBJECT element, new to HTML 4.0, in place of the older EMBED element for including multimedia in your Web pages. The OBJECT element has a clear advantage: while all of the attributes of a multimedia object must be hard-coded into the <EMBED> tag, the OBJECT element's <PARAM> tags allow you to reference an object's attributes using any number of generic NAME/VALUE pairs.
In our example, we're embedding the ActiveX control ActiveMovie into our HTML page to play an .avi file. Although ActiveMovie has a whole list of properties you can control, we've changed the default values of only two: the "Rate" and "FullScreenMode" attributes.
<HTML> <HEAD> <TITLE>New Page</TITLE> </HEAD> <BODY> <OBJECT ID="ActiveMovie1" WIDTH=267 HEIGHT=75 CLASSID="CLSID:05589FA1-C356-11CE-BF01-00AA0055595A"> <PARAM NAME = "Filename" VALUE = "tomato.avi"> <PARAM NAME = "Rate" VALUE = "2.0"> <PARAM NAME = "FullScreenMode" VALUE = "4"> </OBJECT> </BODY> </HTML>
Now, if ActiveMovie's creators want to add attributes to their object, we don't need to also add them to the <EMBED> tag, but simply reference them with an additional NAME/VALUE pair when we want to use them.
Note: The OBJECT tag is new with HTML 4 and older browsers may not recognize the tag. If you expect that readers with older browsers will be viewing your page, you might want to continue using the EMBED element until HTML 4 becomes more widespread.
ZD Journal's Microsoft Web Builder journal
If you have links on your page that will take users away from your site, consider having the links open a new window rather than having the new page open in the current window. That way, your users continue to have your own site in view, and may be more likely to return to it by just closing the newly opened window. Using the Window object's open method allows you to not only open a new browser window, but also allows you to specify the window's size and look.
The open method accepts three parameters: A URL to be loaded into the window, an optional name for the window, and an optional string of window features that will determine what the window will look like. For example, the window features can specify whether the window should have a menu bar, location bar, status bar, or scrollbars. They can also specify the size of the window and whether or not it should be resizable.
The list of window features that you want your new window to exhibit are placed inside a quoted string, separated by commas, and with no spaces anywhere within the string.
Here's an example. To open a new window when a link is clicked, set up the link like this:
<A href = "javascript:openwindow('http://www.zdjournals.com')">Check out
ZDJ's Daily Buzz!</A>
Then, to open a new, unnamed window with a status bar and scrollbars that is 400 pixels high and 600 pixels wide, and is resizable, the script would be:
<SCRIPT>
function openwindow(address) {
window.open(address,"","status,height=400,width=600,scrollbars,resizable")
}
</SCRIPT>
For a full list of the open method's window features, see the Microsoft site at:
http://msdn.microsoft.com/workshop/Author/dhtml/reference/methods/open_0.asp 
ZD Tips
Unlike many other programming languages, JavaScript does not have a built-in function for formatting floating-point numbers. However, it's easy to create one using JavaScript's String methods. Try this:
function format(expr, decplaces) {
// Convert the number to a string
str = expr.toString()
// Get the position of the decimal point
point = str.indexOf(".")
// Get the substring to the correct decimal place
newstring = str.substring(0, Number(point) + Number(decplaces) + 1)
//Convert the string to a number, and return
return(Number(newstring))
}
To call the function, just substitute the number you want to format for the first parameter, and the number of decimal places you want in the second parameter. For example, if you wrote these statements:
x = 23.56733 newnum = format(x, 2)
then the value of newnum would become 23.56.
ZD Journal
You can define your own colors for displaying the state of your links using the CSS1 anchor pseudo-class. The anchor pseudo-class works with link state information to allow you to define a color for different states of your link:
* visited: you've clicked on the link, and visited the site.
* unvisited: you have not yet visited the site.
* hover: your mouse is held over the link.
* active: your mouse button is being pressed while over the link, but the button is not yet released.
Below is a page that demonstates the anchor pseudo-class:
<HTML>
<HEAD><TITLE>Tags example</TITLE>
<STYLE>
A {color:yellow}
a:hover {color:red}
a:visited {color:lime}
a:active {color:purple}
</STYLE>
</HEAD>
<BODY>
<a href = "http://www.zdjournals.com" > Great technical journals! </a>
<BR>
<a href = "http://www.zdtips.com" > Free technical tips and tricks! </a>
<BR>
</BODY>
</HTML>
When your mouse is over each of the links, the font color for the link turns red. When you press down on the mouse button over the link, the link turns purple, and when you release the mouse button, and you are taken the site, the link turns green.
For the unvisited state, the codes takes a little different approach: applying a style definition to the A element, as in A {color:yellow}, has the same effect as a:unvisited - the link is yellow in its initial, unvisited state, and then changes color as the link changes state.
ZD Journals' Microsoft Web Builder journal
The appVersion property of JavaScript's Navigator object returns the version of the current browser, along with information about the browser's platform. For example, running Internet Explorer 4.0 in Windows 95 would create the following value for the appVersion property:
4.0 (compatible; MSIE 4.01 Windows 95)
You might, at first glance, assume that you can simply extract the first character of the appVersion string to determine the version of Internet Explorer that you're using. However, that first number is the compatible Netscape version; the Internet Explorer version is actually to be found in the string "MSIE 4.01." To extract the Internet Explorer version from the string, try using a combination of the indexOf() and charAt() String methods, as in:
function getversion()
{
//Get the position of the string "MSIE" in the appVersion string
position = navigator.appVersion.indexOf("MSIE" )
//If the string is found
if (position >-1)
{
//Move to the position of the version number and test
switch (navigator.appVersion.charAt(position+5))
{
case "3":
alert("Using Internet Explorer 3")
break
case "4":
alert("Using Internet Explorer 4")
break
case "5":
alert("Using Internet Explorer 5")
break
}
}
else
alert("Not using Internet Explorer")
}
ZD Tips
The ID property of the <DIV> tag allows you to give a unique name to a block of text on your page that you can then access dynamically. In the example below, we've put <DIV> tags around an H1 element and given the ID property the value heading. We can then use the ID property to refer to that section of text by using IE 4's object model, as in: document.all.heading.
The simple example below illustrates how you can use the DIV ID to change one of the style properties for our heading on the fly:
<HTML>
<HEAD><TITLE>DIV Example</TITLE>
<SCRIPT LANGUAGE = "jscript">
function change() {
document.all.heading.style.color = "red";
}
</SCRIPT>
</HEAD>
<BODY>
<DIV ID = heading STYLE = "color: blue" onclick = "change()">
<H1> This is a piece of text that you can change dynamically. </H1>
</DIV>
<BODY>
</HTML>
We've only illustrated one simple example of how the DIV tag can be put to work; once you've identified a portion of your Web page using the ID tag, either image or text, the possibilities are endless.
ZD Journal's Microsoft Web Builder journal
While the DIV element can be used to designate block-level elements such as paragraphs and list items, SPAN is used within a block. And while most browsers will insert a line feed before and after the DIV tags, the text within the SPAN tags remains on the same line as the rest of the text in the larger block.
In the simple example below, we've used the SPAN element and Cascading Style Sheets (CSS) to set the text of the entire paragraph to green, except for the words "SPAN element", which appear in blue. Note that all of the text will appear on one line.
<HTML>
<HEAD>
<TITLE>SPAN tip </TITLE>
<STYLE>
P {color: green}
.special {color: blue}
</STYLE>
</HEAD>
<BODY>
<P>This is an example of how you can use the
<SPAN class = special > SPAN element </SPAN>
in your Web pages.
</BODY>
</HTML>
You can also trap events within a SPAN element by including one of several event methods within the <SPAN> tags.
ZD Journals' Microsoft Web Builder journal
Use the tags method available through IE 4's object model to dynamically access each element defined by particular type of tag. Given a string that specifies a type of tag, the tags method returns a collection of all the elements within tags of that type. The position of each element in the collection depends on its location on the page; i.e., the first occurrence of the tag is the 0th element in the collection, the second occurrence is the 1st element, etc. To access a particular element within that collection, we can then use the item method, which accepts an index into the tags collection, and returns the element at that position. In our example we dynamically change the color of the <P> element associated with a corresponding heading. When your Web page reader moves his/her mouse over one of the headings, the highlight function changes the color of that particular <P> element to red. When the mouse is moved off, the lowlight function changes the color of that element back to black.
<HTML>
<HEAD><TITLE>Tags example</TITLE>
<SCRIPT LANGUAGE = "JSCRIPT">
function highlight(num){
var myelement = document.all.tags("P").item(num);
myelement.style.color = "red";
}
function lowlight(num){
var myelement = document.all.tags("P").item(num);
myelement.style.color = "black";
}
</SCRIPT>
</HEAD>
<BODY>
<H3 onmouseover = "highlight(0)" onmouseout = "lowlight(0)">
Original Recipe</H3>
<H3 onmouseover = "highlight(1)" onmouseout = "lowlight(1)">
Reduced Fat Recipe</H3>
<H3 onmouseover = "highlight(2)" onmouseout = "lowlight(2)">
Non-Fat Recipe</H3>
<P> Linguini Alfredo<BR>
l lb pasta<BR>
1 cup Parmesian cheese<BR>
<P>Linguini with Low-Fat Ricotta<BR>
l lb pasta<BR>
1 cup lot-fat Ricotta<BR>
<P>Linguini with Fat-Free Vegetable Broth<BR>
l lb pasta<BR>
1 cup chicken broth<BR>
<BODY>
</HTML>
You can apply the tags method to lots of tag types, including anchors, forms, links, all, scripts, images, applets, frames, embeds, areas, elements, and plugins.
ZD Journal's Microsoft Web Builder journal
IE 4's TextRange object contains the text of the HTML element that created the object. Use the createTextRange method to create a TextRange object, and the other TextRange methods to query, copy, and manipulate the objects HTML text.
In our example, document.body.createTextRange creates a TextRange object holding all of the text in the body of the current document. We then use two TextRange methods: findText and pasteHTML. When your Web page reader types some text in the textbox and clicks on the Find button, the ChangeText function creates a TextRange object named newText. The findText method searches newText for all occurrences of the users text. The pasteHTML method then pastes new text back into the newText object for each occurrence it finds. The result: the color of all occurrences of the text the user has entered changes from the original green to red..
<HTML>
<HEAD><TITLE>TextRange example</TITLE>
<STYLE >
P {color: green}
FONT.change {color: red}
</STYLE>
<SCRIPT LANGUAGE = "JSCRIPT">
function ChangeText() {
var newText = document.body.createTextRange();
if (tochange.value != "")
while (newText.findText(tochange.value))
newText.pasteHTML("<FONT class=change>" + tochange.value + "</FONT>");
}
</SCRIPT>
</HEAD>
<BODY>
<P>
To highlight all occurrences of a word in the document, enter the word here:
<input name = "tochange">
<input type = "button" value = "Find text" onclick = "ChangeText()">
<P>A line of text.
<P>Another line of text.
<BODY>
</HTML>
You can use the createTextRange method to create TextRange objects of BODY, BUTTON, TEXT, and TEXTAREA, and INPUT elements.
ZD Journal's Microsoft Web Builder journal
Since Netscape and Microsoft have different object models, a different script might have to be written for each type of browser. To make matters a little easier, you can write your IE-compatible script using JScript, write your Navigator-compatible script in JavaScript, and place the JScript block after the JavaScript block. Since Navigator ignores JScript, it will process the JavaScript block. Although IE can parse both scripts, it will process the the JScript block instead, since a brower will process the bottommost scripting block that it is capable of parsing.
ZD Journals' Microsoft Web Builder journal