Xhtml The New Standard For The Web

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Xhtml The New Standard For The Web as PDF for free.

More details

  • Words: 32,345
  • Pages: 76
Homepages for experts © Copyright Johann-Christian Hanke

Acrobat Reader: How to ... F5/F6 open/closes bookmarks - F4 open/closes thumbnails In menu View you can set, how the file is displayed CTRL+0 = Fit in Window, CTRL+1 = Actual size, CTRL+2 = Fit width You can set SINGLE PAGE, CONTINUOUS VIEW or CONTINUOUS FACING .. try them out and you will see the differences.

Navigation ARROW LEFT/RIGHT: forward/backwards one page ALT+ARROW LEFT/RIGHT: same as in a browser: forward/back CTRL++ zooms in AND CTRL +- zooms out

www.knowwareglobal.com

Table of Contents Hello .....................................................................................4 XHTML: The New Standard for the Web........................5 XML as the “Language” of the Future....................................... 5 Advantages of XML .................................................................. 6 Disadvantages of XML .............................................................. 6

Differences between HTML and XHTML........................7 Basic Structure of an XHTML Document ........................8 HTML TIDY, HTML Kit, and 1st Page by Evrsoft..........9 Java, JavaScript, Objects, Properties, and Methods .......10 The Idiosyncrasies of JavaScript ............................................... 10

Let’s go, let’s go: Integrating JavaScript Code in (X)HTML .........................................................................11 Input, Output, and Variables .............................................12 Calculating with JavaScript ...............................................13 Redirection with JavaScript and via <meta> Tag............14 Simple Redirection .................................................................... 14 Timed Redirection ..................................................................... 14 Redirection via <meta>-Tag ...................................................... 14

Simple Password Protection with the if statement ...........15 Making Decisions with if........................................................... 15 Comparison Operators ............................................................... 15

Decision Making: Reacting to User Input.........................16 The Switch Command ............................................................... 16 Changing Background Colors.................................................... 16 Redirection................................................................................. 16

Here’s how you program a for loop...................................17 Looping another way: while ...............................................18 Password Protection with Exit Condition .................................. 18

JavaScript Functions and Event Handlers .......................19 Defining a Function ................................................................... 19 Event Handlers........................................................................... 19 Starting with Buttons ................................................................. 19 How can I call Functions? ......................................................... 20 Function with Parameters .......................................................... 21

JavaScript inline and external: Navigation Buttons and Links..........................................................................22 Hyperlinks with JavaScript ........................................................ 22 The history Object ..................................................................... 22 Storing JavaScripts as Separate Files......................................... 23

Programming your own Windows with JavaScript .........24 Windows as Remote Control Objects ........................................ 25 Creating Windows „on the fly“.................................................. 26

Extracting Information from the Surfer and Reacting to it ....................................................................................27

3

Font Tags....................................................................................37 Adding Sound Files and Videos .................................................38 Incorporating and Formatting Moving Text ...............................38 Tags for Forms ...........................................................................39 Anchors and Hyperlinks .............................................................40 Tags for Tables ...........................................................................40 Tags for Framesets .....................................................................41

Style Sheets: The Most Important Attributes of CSS ..... 42 Attributes for Changing Font Properties.....................................42 Attributes for Formatting Lists ...................................................43 Text Alignment...........................................................................43 Formatting Borders and Frames .................................................44 Color and Background Graphics ................................................45 Absolute Positioning (important for DHTML)...........................45

Units of Measurement, Colors, and Special Characters . 46 The Most Important Colors ........................................................46 RGB Color Codes for CSS .........................................................46 Codes for Special Characters......................................................46 Country Codes for Character Sets ..............................................46 Hover Links ................................................................................46 Units of Measurement for CSS...................................................46

Navigating More Comfortably with Pull-down Menus... 47 Pull-down Menu with Go Button................................................47 Pull-down Menu with onChange ................................................49 Pull-down Menu in a Frameset...................................................49 Creating the Frameset.................................................................49 The Navigation File....................................................................50

Changing Several Frames at one Time............................. 51 Changing Two Frames at Once ..................................................51 The Hierarchy in Frames ............................................................52

Further Tips and Tricks for Frames................................. 52 More Dynamic, Please: Changing Text and Tickers....... 54 Displaying Changing Text in Form Fields .................................54 Changing Text on the Status Line ..............................................55 Programming a Ticker: The String Object in Brief ....................55 Typewriter Ticker with the substring() Method..........................56

Evaluating Forms with JavaScript ................................... 58 What’s Behind CGI ....................................................................58 FormMail as an Alternative to mailto.........................................58 The Example: An Order Form in HTML....................................59 Preventing Accidental Reset and Submit....................................60 The confirm() Box ......................................................................60 The Script for Capturing the Events ...........................................60

Checking Form Field Entries ............................................ 61

The screen Object ...................................................................... 27 Netscape or Internet Explorer? The Browser Question! ............ 27

Checking Fields to see if Anything was Entered ........................61 Checking the Validity of E-Mail Addresses ...............................62 Calculating the Result.................................................................63

Some Mathematics: Random Numbers with the Math Object ...............................................................................30

Mouseover Effects and Banners........................................ 64

The Math Object ........................................................................ 30 Script for the Dice Game ........................................................... 30

More Fun with Arrays: Random Links and Jukebox......31 An Overview of Arrays.............................................................. 31 The Script for the Random Links............................................... 31 Abbreviation .............................................................................. 31 Programming a Jukebox ............................................................ 32

Reading Out and Displaying the Date and Time..............33 XHTML Reference: The Most Important Commands:...35 General Tags.............................................................................. 35 Paragraphs, Line Breaks, and
.......................................... 35 Tags for Simple Text Formatting............................................... 36 Adding Graphics Files ............................................................... 36 Drawing Lines ........................................................................... 37 Making Lists .............................................................................. 37

OnMouseover Effects with Hover Links ....................................65 Script for a Banner......................................................................66

Programming and Reading Out Cookies ......................... 67 “Recognizing” a Surfer with the Help of Cookies......................67 The cookie Property, setMonth() and Cookie-Syntax ................68 Reading Out One Cookie from among Many .............................68

DHTML: Addressing CSS Containers and Levels .......... 70 Prerequisites for DHTML...........................................................70 The Example: Animating a Graphic ...........................................71 Programming Pull-down Menus with DHTML..........................72 Curtain up and ... Butterfly!........................................................74

Checking JavaScript Code for Errors .............................. 76 Index .................................................................................... 77

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Welcome!

4

Hello ... … here you are again. This new booklet will cover

About the author

• XHTML and CSS • DHTML • JavaScript, JavaScript, JavaScript ...

I’m 32 years old and I’ve been working as a freelance author for various publishing companies and publications for 3 ½ years.

In addition, we’ll talk just a little bit about CGI and we’ll have a brief look at what XML is all about. In the middle section from page 35 onward, you’ll find several reference tables about XHTML and CSS, complete with examples. If you’re clever, you can separate these three sheets from the booklet and lay them flat on your desk. Our main topics will be JavaScript and DHTML (a combination of CSS and JavaScript). You’ll see how easy it is to learn these programming languages and to create interactive pages. After working through this booklet, you should be able to create dynamic buttons, banners, pull-down menus, and interactive forms. You’ll be familiar with functions and event handlers, you’ll know how to manipulate the date and time, set password protection, and program cool JavaScript windows. You’ll divide your pages into frames and manipulate these with JavaScript. But enough of that! We’ll bake “cookies” and greet surfers in quite unique ways. We’ll have a peek behind the curtains of DHTML. You’ll learn what’s behind layers and pixel-exact CSS containers. You’ll program cool pull-down menus, “timeline-effects,” and a little screen show. Warning! This booklet is not intended for beginners! I’m assuming that you’re quite familiar with Windows (and HTML) and that you know what’s behind CSS. Regard this booklet as a continuation of “Get going with Homepages”, my introduction to Web site creation that has already gone through several editions. You can use it in parallel with the booklet “JavaScript” by Martin Baier.

So far, I’ve published titles (in german) on Word, Excel, Windows, StarOffice, Outlook, Works, Internet programming, and MS Office, including the 945-page tome “The Best Office 2000 Secrets,” which, at the beginning of the year 2000, was named “Book of the Week” by ComputerBild. I especially like writing for Michael Maardt and his congenial publishing company. I’ve already written countless booklets for KnowWare, including titles on Outlook, Outlook Express, Word, and PowerPoint. I have him to thank also for allowing me to make this booklet longer than normal without regard to printing costs. In the meantime, from endless writing, I’ve got wornout fingers and bad eyes from staring at the computer screen so much. Make sure that this doesn’t happen to you!

Your opinion counts Download all the exemplary scripts and try out the surfing recommendations to expand your knowledge! Look for the page on the homepage and here you find the link to download the files. You’re missing something? You’ve found an error? My e-mail address is [email protected]. And now I wish you much enjoyment with “Homepages for Experts” and much success pepping up your own publications on the World Wide Web! Think about it: there are more important things in life than computers! Very truly yours, Johann-Christian Hanke!

In this booklet I’ll delve deeper into the basics of HTML, CSS, and the programs I’ve already introduced. I discussed how to upload pages and register them with search engines in “Homepages for Beginners.” This booklet is a kind of invitation for experts to tinker, a collection of JavaScript homepage tricks with countless examples. In addition, I’ll tell you about the new XHTML and XML standards.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

XHTML and XML

5

XHTML: The New Standard for the Web HTML is dead, long live HTML! Why? In January 2000, the World Wide Web Consortium (W3C) declared XHTML the new standard. The W3C? Right! The W3C is a kind of non-profit organization of various interest groups. Firms like Adobe, Microsoft, and Sun belong to the W3C. You can even become a member – if you’re willing to pay $5000 a year for the pleasure. This organization develops recommendations and suggestions for new Web standards. You’d like to know what the “brothers” are “hammering out” now? Your English is just perfect? Then surf by www.w3.org.

You’d like to start the Windows editor even faster? Select START/RUN. Type notepad into the field and press ENTER. Zap! Your text editor is awaiting your command. And here’s another trick: the editor only uses the extension txt when it’s saving files, but you’d like to use xml instead. To force the editor to save files with another extension (xml, for example), type the whole file name in quotation marks, i.e., “knowware.xml”. And now? If you double-click on knowware.xml, it will open in Internet Explorer. Internet Explorer Version 5 will even display the document for you. (Netscape 4.x doesn’t yet understand XML.)

Generally, whatever the W3C recommends becomes the industry standard shortly thereafter. And this is what happened with XHTML. So HTML wasn’t sufficient? Unfortunately not. But don’t despair; you won’t have to learn everything all over again. XHTML is nothing more than HTML. It’s just HTML according to the rules of XML. Therefore, I’ll first explain in brief what’s behind XML! After that, you’ll learn where the differences and commonalities between HTML and XHTML lie so that you can “change over” quickly.

XML as the “Language” of the Future Now on to XML. The “boys” of the W3C invented XML in 1998. XML is the abbreviation for eXtensible Markup Language. Does this ring a bell? No? In XML you can make up your own tags! Let’s try this right now. I’ll show you an overview of an XML document. Here you’ll find information about two KnowWare booklets. Word for Experts Michael Maardt <price>$4.95 Homepages for Beginners Joh.-Christian Hanke <price>$4.95

Type this text in and save it as a normal text document with the extension xml. I’d suggest using knowware.xml as the file name. You can use the beloved Windows editor, Notepad, to create and save the file.

Now that you can see the document in the browser right before your eyes, we should take a closer look at the basic structure of XML.

An overview of XML Have a close look at the first line. Do you notice anything? No? It doesn’t matter. But you should notice anyhow: the XML document begins with a socalled prologue. Here’s where the version of XML and the character set are defined. This ISO-8859-1 is nothing more than Latin 1. In plain English: if your language requires them, you can use umlauts without a problem. (There’s a table with character codes in the reference section in the middle of this booklet.) And here’s something else interesting. The prologue has no conclusion, that is, no end tag. Next comes the root element, here it’s . You can compare this to in HTML. The root element makes the “brackets” and is mandatory in XML. I made up the name of the root element. After this comes the beginning of the true XML romp. You can define your own tags as you wish. I did this unashamedly here; I defined the various tags and nested them one inside the other.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

XHTML and XML

6

For example, a whole booklet can be “bracketed” with . This tag, in turn, contains subtags for title, author, and price: ,, and <price> fulfill this function. And I could expand my little database even more if I wished. Wait a minute – did I just say database? Correct! Each booklet is a data type, the individual “elements” are the data fields. You’ll notice already: XML is ideal for structured data, for example, as it already exists in databases.

Advantages of XML In the future, it is possible that XML will become a platform-independent “document description language.” It won’t matter whether you’re talking about word processing, spreadsheets, databases, Web pages … all programs will be able to read and write XML. Let’s take our “KnowWare Project.” The data for the booklets is nicely embedded in our structure. But you need a printed copy? Nothing could be easier! The XML-enabled word processor will produce one for you. You work in a call center that sells KnowWare booklets? Then connect the XML file with the telephone software. On request, the software will read off data about individual booklets for the customer.

incompatible with one another. Hopefully the clunky and error-prone process of filtering documents will also disappear. Each program will be able to read and write XML. So that’s the good news. And the bad?

Disadvantages of XML Are you ready for the truth? At the moment, XML is not well-suited for creating Web sites. • Only the newest browsers (Internet Explorer Version 5 and above, Netscape Version 6 and above) can even display XML. And what good is the best standard if the majority of surfers can’t see anything? • XML only defines the structure of the document; in contrast to HTML, it can’t define itself. • For the purpose of layout, you’ll need some knowledge of CSS or XSL. Especially the new XSL is not yet fully supported. • Many additional languages to be used with XML are currently under development, that is, they’re not yet standardized and are only partially supported. • For “professional” XML projects, you have to write an additional “document type definition” in which you define the tags and establish their order. • Many things like tables, graphics, hyperlinks, etc. don’t work with XML alone.

You’d like to present the data on the World Wide Web? That’s even possible today! Connect the XML document with a “layout language” like CSS or the new XSL. XSL stands for eXtensible Stylesheet Language.

In short: creating XML projects is quite complicated. Whether a page created this way will even be displayed properly in the browser, only the heavens know. If you make a typo, the browser will produce only an error message.

With XSL you can even display the data in table form, sort it, and filter out individual pieces of data.

Now that we’ve had a look at the future, let’s return to the present. And this is called XHTML.

You’d like to present your document in multimedia form? You’d like to add hyperlinks or even mathematical formulas? XML is flexible and allows the construction of your own language. There are already several of these out there. SMIL is responsible for representing multimedia contents. Xlink serves to create hyperlinks, and MathML can create formulas. If you want to represent vector graphics, you’ll need to use SVG. Here’s the wonderful thing: with all these languages, we’re talking about open, license-free standards. Anyone can see them, understand them, and use them. In the future it won’t be necessary for software producers to keep tending their file formats that are

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

XHTML and XML

7

Differences between HTML and XHTML So in the next few years HTML will remain the reigning standard. But since XML already exists, the “movers” of the W3C are thinking: “let’s turn HTML upside down!” XHTML is HTML according to the strict rules of XML! Since you already know HTML, I’ll give you an overview of the particulars of XHTML. Ö Restrict yourself to lower case: In HTML, upper and lower case were the same. In XHTML, however, tags and attribute names can only be written in lower case. (Only the attribute values can still be written in upper case.) I find this rule to be a good thing. Lower-case letters are more practical since you don’t have to hold down the [Shift] key the whole time. Ö Each tag needs an end tag While in HTML you could get quite sloppy, and this was even supported by leading HTML developers, in XHTML, each tag needs to have an end tag. The omission of

or is forbidden. So write:

This is a paragraph



This too is a rule that strives for unity and that I therefore find good. Ö Tags without end tags must be closed Nowadays, tags without end tags must be closed; internally, that is. Once upon a time, you could write a line like this:


Right now, you can choose how to write this line:


Ö Attribute abbreviations are no longer allowed Previously, you could freely choose to use the abbreviated name instead of the full name of an attribute value. Using you could set up borders, using
you could suppress shadows of a line, and

ensured that an option field was chosen. Now, abbreviations are forbidden; you need to write out the full attribute value. In our examples, this would mean


and


and

Ö Attribute name is replaced with id Do you remember the attribute name in HTML? It serves to name anchors, forms, etc. It has now been replaced completely by id. Unfortunately, older browsers can do nothing with id. Therefore, it’s best if you put both attributes in and give them the same value or omit id. Let’s assume that you want to define an anchor. Then you’d write:

If you want to name a form, you’d do it as follows:

Here you use an empty space and after that, within the tag, a slash. The empty space is necessary so that older browsers (Netscape 4.x, for example) won’t become confused. These browsers handle the slash as an additional, unknown attribute, which they ignore. So in XHTML it would be more correct to write the line like this:


Then the line will not be displayed everywhere. This rule takes some getting used to! Ö Attribute values must be placed in quotation marks Now you need to place all attribute values in quotation marks, for example, like this:


This rule takes care of the conformity problem!

... Form Contents

Ö Scripts and CSS are “hidden” in SGML Now scripts and CSS references in SGML references are supposed to be “hidden,” for example, like this: <script language="JavaScript" type="text/javascript">

The reason for this is that special characters like & or > supposedly would confuse XML-capable browsers. I would advise you to ignore this since at this point there are no browsers that would be confused by this.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

8

Basic Structure of an XHTML Document

Basic Structure of an XHTML Document Up to this point, these are the most important developments. But something is missing! XHTML is XML that works with HTML tags. And an XML document begins with the prologue. Right, and proper XHTML also begins with this prologue. Next comes the reference to the so-called document type definition. The document type definition resides on the W3C’s server; this is where all XHTML tags are defined. For example, let’s choose “transitional DTD,” the transitional version. It isn’t quite so strict. The third line is still missing. And here is where the tag finally comes, albeit with the attribute xmlns. This is the “namespace attribute,” which in XML defines a “namespace” for HTML. The rest is pure HTML with the special XHTML particulars! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

In this booklet, I’m not writing 100% correct XHTML; instead I’ve made a XHTML Document compromise. I combine lines 1-3 and remain true to current practice. And

KnowWare Title

why not! At this time, the reference to

Word for Experts

DTD is useless anyway. No browser
  • Michael Maardt
  • cares about it and actually reads out the
  • Price: $4.95
  • DTD! Finally, all current and future
browsers recognize the HTML tags.
They are built firmly into the browser.

Homepages for Beginners

    If you’d like, you can use the converter
  • Joh.-Christian Hanke
  • TIDY (see the next page) to transform
  • Price: $4.95
your document into correct XHTML at any time.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Cool Tools for Checking Syntax

9

HTML TIDY, HTML Kit, and 1st Page by Evrsoft What tools do you use to code your pages? The Windows editor Notepad? Homesite? Uli Meybohms HTML editor Phase V? Or perhaps you even work secretly with Frontpage, Dreamweaver, or GoLive? It doesn’t matter; at least you know that you can’t get around HTML or XHTML. And you also know that especially with “hand-made” code, many typos can remain.

Checking syntax So how do you work with TIDY and the HTML Kit? It’s easy. Press the Hot Key [F9]. In a flash, your document will be checked and corrected. On the lower part of the window you’ll see a report about each mistake; the correction is on the right.

You’ve made mistakes, for example, you’ve forgotten or ? Then the Netscape browser will be particularly upset with you! In case of doubt, your page can’t even be displayed. Just test your code before uploading it.

HTML Kit with HTML TIDY Dave Raggett (a leading developer of HTML and a member of the W3C) has written a neat tool that you can use to check your pages for mistakes. It’s called HTML TIDY and you can find it at • www.w3.org/People/Raggett/tidy

The most practical feature of TIDY is exactly this “split view.”

where anyone can download it for free. You should be aware that this program works commando-style. Luckily, however, there is a wondeful “shell” for TIDY. May I present to you:

If you’re satisfied with the result, right-click on the right-hand side. Here you’ll select the command Copy All to Editor. Then save your document.

The HTML Kit, a small but elegant HTML editor that is up to the task.

And the best is yet to come: HTML Kit can, with the help of TIDY, convert your document to XHTML or even XML.

You should definitely download it from

Converting to XHTML

• www.chami.com/html-kit Preferably right away. Install it.

From the Action menu, select Tools. Point to HTML Tidy, then Convert to XHTML. And if that’s not enough, you can use the Upgrade to Style Sheets command to transform your tags into CSS. Another great editor with TIDY support is 1st Page from Evrsoft, which is also available for free. 1st page is an imitation of Homesite; you’ll find it at www.evrsoft.com/download. This tool also contains many pre-prepared script examples.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

10

Java, JavaScript, Objects, Properties, and Methods

Java, JavaScript, Objects, Properties, and Methods For most of the effects described in this booklet, you’ll need some JavaScript knowledge. So now I’ll teach you quickly about the basic expressions of this easy programming language. JavaScript doesn’t have anything to do with Java. Java is a well-developed programming language for complex applications. JavaCode must be created in a development environment and compiled (translated into machine language). While Java was developed by Sun, JavaScript originated with Netscape.

The Idiosyncrasies of JavaScript What do you need to know about JavaScript? Not a lot: • You write the code in plain English in the HTML document. • JavaScript code is unprotected and can be read and copied by anyone. • The program’s instructions are carried out “during execution,” that is, while the browser is loading the page. • JavaScript is not bound to a particular operating system and (normally) not to a particular browser type. • JavaScript is (luckily) really fairly weak; it cannot delve deeply into the system or save documents. It’s a small scripting language whose only purpose is to “pep up” Web documents. Microsoft’s answer to JavaScript is called VBS or VBScript (Visual Basic Script). VBScript is built firmly into Windows and Internet Explorer, but it doesn’t work in other browsers. VBScript is dangerous since it allows deep incursions into Windows. The e-mail virus ILOVEYOU was programmed in VBS. This is another reason that speaks against VBS and for JavaScript. I would strongly advise you to stay away from VBS.

JavaScript is object-oriented

In an object-oriented language, one speaks of objects, properties, and methods. Ö Objects You can regard an object as a thing. Outside of programming, it’s a cat, a book, a car. In the program itself it is, for example, the object window (program window) or the object navigator (browser). Ö Properties Objects possess properties. The cat has an age, the car a particular color. Using properties, you can describe objects more precisely. For example, you can write Cat.Age=5 Car.Color=black

or (to use a “real example”): window.location="index.htm" navigator.appName="Netscape"

whereby the property location of the browser window object is assigned the value index.htm and the appName property (the application name) is made more precise with Netscape. Properties describe objects more precisely. Imagine objects and properties as “nouns” and “adjectives,” respectively. Ö Methods Methods are the actual actions. A cat meows, a car drives: Cat.meow() Car.drive()

A browser window is opened or closed

JavaScript is a modern programming language that is based on a graphical interface. Therefore, it’s designated as object-oriented. As a reminder: behind the graphical interface lie the browser window and its elements!

window.open() window.close()

Just to give you a scare, I’ll show you the most important objects in JavaScript and their hierarchy.

document.write("Hello, my Friend")

The methods are designated by round brackets (parentheses). In some cases, there will be more precise references here too. With this text is displayed in the browser window. Methods are actions; think of them as “verbs.”

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Integrating JavaScript Code in (X)HTML

11

Let’s Go: Integrating JavaScript Code in (X)HTML You didn’t understand a word of what I explained on the previous page? Don’t worry – I only understand half of it myself. Just get used to the terms and watch out for the odd dot notation. You go from left to right, from the general to the concrete. And one more thing that you should notice right off the bat: as a rule in JavaScript, each line ends with a semicolon. You aren’t allowed to use a semicolon with function, if, else, while, etc. Enough prelude. You’ll learn JavaScript best using practical examples! In the next few pages I’ll teach you some basic terms.

Hello, my Friend: integrating JavaScript in HTML And how do you integrate JavaScript into HTML? Nothing could be easier! The following script displays the text Hello, my Friend. To do this, we’ll use the write() method of the document object. The file name is hello.htm; you’ll find the document in the start folder. I’ve highlighted the actual script: 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13.

My First Script <script language="JavaScript" type="text/javascript">

Here are the real contents ...



It’s best to write the script into the header area of the HTML document. The customary place is between and . Line 4 shows you how to open a script. The tag <script> by itself might suffice, but the attributes language and type are mandatory. In Line 8, the script is closed again using . Line 5 contains the open comment character , see Line 7. Line 6 contains the actual script lines. Don’t forget to end the line with a semicolon.

Work with comments! So that later on you’ll still know what your script means, I recommend working with comments. A one- or multiple-line comment is enclosed in /**/; simple comments come after //: /* This is a comment, one that can even take up more than one line */ document.write("Hello, my Friend!"); // This is a short comment

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Input, Output, and Variables

12

Input, Output, and Variables Let’s go ahead and get started with “real programming.” You’ll get to know an input box and an output box. So that we can begin working with these boxes, I’ll first introduce you to these great variables.

What are variables? Variables are “variable placeholders.” They are storage spaces in the main storage of your computer. They can store values for the duration of a program. It doesn’t matter whether the variables hold numbers or text (a socalled string). JavaScript tries to recognize the data types all by itself. You can think up your own names for variables, for example, name. Avoid strange characters (umlauts, for example) and empty spaces.

The prompt() method With prompt(), you create an input box. The surfer can type something in here. Prompt is almost the same as keyword. Here’s the syntax: prompt("Commandtext","Defaultvalue")

The resulting box is created by the code prompt(“Please type in your name”, ""). As a rule, the Defaultvalue remains empty, so leave the space between the second two quotation marks empty.

The alert() mthod With alert(), by contrast, you display a message in a dialog box. If, in alert(), prompt() or other boxes, you want to include an umlaut, type it uncoded, that is, as ä, ü, ö, etc. Don’t use ä or ü or ö otherwise, the character won’t appear properly.

I’ll show you a script that integrates all three elements with one another. Build it into an HTML document: <script language="JavaScript" type="text/javascript">

In the first real code line, the variable is declared with the keyword var. You don’t have to do this, but it’s a good idea. In Line 2, you assign the variable the value that the surfer types into the prompt() box and confirms by clicking OK. In such an assignment, the variable must be on the left-hand side. Here, the = is a so-called assignment operator. Line 3 connects the contents of the variable with two text strings. Text strings must always be placed in quotation marks. The content of the variable and the text strings are combined with one another using the string operator +. Watch the number and placement of empty spaces when you’re working with text strings; for example, you’ll need an empty space after the comma in Nice to meet you, . Compare this with the file variable.htm in the start folder.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Calculating with JavaScript

13

Calculating with JavaScript You’d like to calculate with JavaScript? Then first you should use the four mathematical operators that you’ve met in Excel or other spreadsheets: +, -, *, and /. In addition, there are ++ and --, which increment a value by 1 or -1, respectively. We’ll learn more about ++ and – when we talk about for loops. Operator

Meaning

Example

+

Addition

a=10+c

-

Subtraction

c=b-1

*

Multiplication

10*3

/

Division

x/y

++

adds 1 to

i++ (this is nothing more than an abbreviation for i=i+1)

--

subtracts 1 from

i-- (stands for i=i-1)

You should also be aware that in JavaScript, the character used to designate decimal parts is the dot (.), not the comma that many Europeans use.

Multiplication as an example of calculation Here’s an exemplary script for simple multiplication; you’ll find it in the file mult.htm. Multiplication <script language="JavaScript" type="text/javascript">

The Great Multiplier

<script language="JavaScript" type="text/javascript">

The result is calculated by multiplying a and b; the result is saved in the variable result. A second script displays the result again right in the middle of the document. Watch out: the operator + serves not only as a mathematical operator, but also as a string operator. You can use it to connect strings to one another. This is how you get the string knowware from “know” + “ware”.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Redirection to Other Pages

14

Redirection with JavaScript and via <meta> Tag Redirection: something we often need. You have a new address and you’d like to steer users away from the old one? Then just redirect them.

the page target.htm (or whatever you’ve entered there!). You’d like to accommodate surfers who have deactivated JavaScript? Then add a link in the source code, something like this: If you are not redirected, please click here Target page.

Timed Redirection You’d like to redirect the surfer after 5 or 10 seconds? No problem. This is a good opportunity to introduce the JavaScript “timer.” Here’s how to use the so-called setTimeout() method. Here’s the syntax: setTimeout("Reference",Milliseconds)

Place the reference in quotation marks. With JavaScript, this is really and truly easy. First I’ll show you how you can direct the surfer immediately to a new page. But a timed redirect is also possible.

Simple Redirection First we’ll explore the question of how instead of loading the current page, you can load another page into the browser window. This is accomplished with the keyword location.href.

Important note: what happens if you’re placing a reference in quotation marks that’s already in quotation marks? That is, you’d like to nest the quotation marks? Then use a simple apostrophe (‘) for the inner quotation marks! Back to our example. The redirection should take place after 5 seconds. Just replace the code in Line 6 with the following: setTimeout("location.href='target.htm'",5000 );

So you’d like to display the document target.htm in the browser window instead of the current page? Then write

You’ll find the result in the file redirect2.htm.

location.href="target.htm"

OK, so the redirection works without any JavaScript at all. Use a so-called <meta> tag for this purpose.

A simple redirection script doesn’t have to contain anything more than this line. Copy this file and save it using the name redirect1.htm. In addition, you’ll need to create a page called target.htm (for example, you can reference an external address such as http://www.knowwareglobal.com) 1 2 3 4 5 6 7 8 9 10 11 12 13

Simple Redirection <script language="JavaScript" type="text/javascript">

We have moved!



Redirection via <meta> Tag

I talked about <meta> tags in the beginners’ booklet. You can place them either above or below . Make sure that you include the required slash (/) with a “compatible empty space” so that your code will conform to the XHTML standard. Type in the following source code. Please put everything on one line; the line break in this booklet is due only to the narrow columns. <meta http-equiv="refresh" content="5;URL=target.htm" />

The 5 refers to 5 seconds. Please make sure that you use quotation marks exactly as I’ve done here. And type the keyword URL in capital letters. The big advantage of this kind of redirection is that even Netscape 2 or Internet Explorer 3 recognize it, even without JavaScript! You’ll find this example in the file redirect3.htm.

Truly, the only important reference is in Line 6. And just as soon as you call up this document, you’ll see

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Decision-Making Structures: if and switch

15

Simple Password Protection with the if statement Up to this point, our programs have run quietly from top to bottom. But it’s precisely the decision-making structures that allow you to add the necessary portion of “intelligence” to your scripts. Let’s try this out with two simple examples. I’ll show you the if and switch statements.

Making Decisions with if First the bad news: secure password protection isn’t possible with JavaScript. Exclamation point! For at some point, the password must be slipped into the source code. But for many purposes, the following script is entirely sufficient. First I’ll show you the syntax of the if statement: if (Condition) { Case A; } else { Case B; }

Pay attention here to the placement of parentheses. In the lines with curly brackets, you don’t need a final semicolon. And here’s the complete script; type it into an HTML document. I’ll explain the source code a little later. You’ll find the script in an HTML document with the name pass1.htm: 1 2 3 4 5 6 7 8 9 10 11

var a, b, c, password; a="are"; b="kno"; c="w"; passwort=prompt("Please enter the password!",""); if(password==b+c+c+a) { location.href="target.htm"; } else { alert("Sorry, you don’t know the password!"); }

First, four variables are declared. The variable password should be self-explanatory. But a, b, and c? They serve only to “mask” the password knowware. You could, of course, spare yourself these variables. Then Line 6 would look as follows and the password would be much too obvious: if(password=="knowware") {

In my version, therefore, the password is “glued together” with the help of the string operator +. Line 5 places a prompt() box right under the surfer’s nose and saves whatever is entered there in the variable password. In Line 6, the result is compared to the password. The double equals sign (==) is a comparison operator. And the concatenation b+c+c+a in the example creates nothing more complicated than the string knowware. Is the condition true? Then Line 7 goes into effect and the surfer is redirected to the page target.htm. If not, then the else statement takes over (else as in or else) and displays the alert() box from Line 10.

Comparison Operators Comparison operators? Greater than, less than, equal to, or not equal to? You’ll need these in JavaScript! Here’s an overview: Operator

Meaning

Things to Watch Out For

==

equals

double equals sign, to distinguish it from the assignment operator =

!=

not equal

>

greater than

<

less than

>=

greater than or equal to

<=

less than or equal to

&&

and

double ampersand

||

either or

under Windows, you can create the vertical line using Shift and the backslash (\) key on your keyboard.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Decision-Making Structures: if and switch

16

Decision Making: Reacting to User Input You’d like to react differently to different user input? Then you can nest several if statements one within the other. But there’s a much more elegant solution: the switch command.

The switch Command Here you can kill several birds with one stone. The syntax is as follows: switch(Variable) { case Value1: Command; break; case Value2: Command; break; case Value3: break; ... default: Command; }

Agreed, this example is not exactly worthy of an Oscar. And in this form it will only work with Internet Explorer and Netscape 6 and up. But I just wanted to show you a simple example so that you’ll understand the principle of the thing!

The switch command checks to see whether the value of a variable equals one of the listed values. If so, then the corresponding command is carried out. The program execution is then ended with the keyword break. If no value matches, then the default: command will be carried out.

Changing Background Colors In this example, the surfer is supposed to type in the name of the desired background color. There are three colors from which to choose: red, yellow, and gray. The line document.bgColor is responsible for setting the background color. With the command document.bgColor="red", you are setting the background color to red. The keyword yellow stands for yellow and gray stands for gray. And here’s the script; see also switch.htm: var color; color=prompt("Type in red, yellow, or gray!",""); switch(color) { case "red": document.bgColor="red"; break; case "yellow": document.bgColor="yellow"; break; case "gray": document.bgColor="gray"; break; default: alert("Unfortunately, these are the only colors available!"); }

The surfer types in (hopefully) red, yellow, or gray. The switch command jumps to the corresponding value and carries out the appropriate command. Whatever you do, don’t forget the keyword break. If the variable (whatever the surfer has typed in) doesn’t correspond to any value, then the default: command will be carried out. This is the fallback position.

Redirection Now let’s create a script that will redirect the surfer to a particular page if the correct password is entered. In our example, we’re concerned with the passwords abc (which leads to the page target1.htm), acb (target2.htm) and bac (target3.htm). var password; password=prompt("Enter the password!","") switch(password) { case "abc": location.href="target1.htm"; break; case "acb": location.href="target2.htm"; break; case "bac": location.href="target3.htm"; break; default: alert("The password is incorrect!"); }

You’ll find this script in the file pass2.htm. Have a look at this example and note that the passwords are in plain English in the script. For increased security, I recommend that you store the script externally. More about this later on!

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Looping with for and while

17

Programming for Loops Loops are very important in a programming language. With the for loop, you can arrange things so that a command is repeated as often as you want. The for loop is sometimes called a counting loop. Here’s the syntax of a for loop: for(Initialization;Condition;Counter) { Command to be carried out as long as the Condition is true } Here’s what to do if the Condition is false

Be sure that the Command to be carried out is enclosed in curly brackets. In JavaScript, you place passages in functions, loops, decision-making statements, etc. that belong together in curly brackets { }. This creates what is called a block. This block-writing takes some getting used to. I recommend the writing method that I use: always type the opening bracket at the end of the line. You should use a separate line for the closing bracket. And here’s another rule of thumb: if you place an opening curly bracket, then that line cannot end with a semicolon. Clear? The programming convention that has emerged is to use an i as the counter variable. Of course you can replace the i with fred, eraser, or flyspeck if you wish. But the joke is that this variable will constantly be incremented by 1, so you could write i=i+1. But since JavaScript programmers are lazy, they like using the abbreviation i++. The next script writes a line into the document for as long as you’ve specified in your input. During execution, the lines are numbered throughout. var i, z; z=prompt("How many times should the text be written?",""); for(i=1;i<=z;i++) { document.write("Line " + i + ": JavaScript is easy!
"); } document.write("The job is done.");

First you ask the user for a number; this value is stored in the variable z. Then comes the counting loop. The start value (initialization) is 1 here. As long as i remains smaller than or equal to z, i is incremented by 1 (i++). As long as the condition is not fulfilled, the program will write the line JavaScript is easy into the document and create a line break (
) after that. Even this is possible! When the condition is fulfilled, the loop stops and the program continues underneath the block. You’ll find the script in the file for.htm. We’ll use loops a lot later on! When using loops, be careful that the condition is one that will be fulfilled; otherwise, you’ll create an endless loop that the surfer can’t break out of!!!

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

18

Looping with for and while

Looping Another Way: while Up to this point, the so-called while loop has been left out of our discussion. This loop checks to see whether a condition is true. Here’s the syntax: while (Condition) { The Code that should be carried out, as long as the Condition is true } Here’s what happens if the Condition is (finally) false.

Let’s just take another look at our “bestseller,” the password program. You’ll find the following script in the file while.htm. var password; while(password!="knowware") { password=prompt("Enter the password!",""); } location.href="target.htm";

First a variable with the name password is declared. But since this variable doesn’t have a value yet, the loop will run through the first time. The condition is that password!=”knowware”, that is, “password does not equal knowware”. And as long as this condition is true, the loop will run. Now (hopefully) the surfer will type the word knowware into the prompt() box. This input is stored in the variable password. Then the loop will test the condition the second time. And now? Now the condition password does not equal knowware is not true anymore, so the loop will end. The code underneath this (the redirect) will be executed and the surfer will finally see the secret target page. If the surfer doesn’t know the password, they’ll be stuck in the loop. This is an endless loop!

Password Protection with Exit Condition You should build an exit condition into the loop. As an additional variable, you could initialize a counter i with the value 1. Now the loop will also check to see (&& means and) whether the counter is less than 3. Since in the loop i++ increments the variable to 3, the loop will break off at the latest after the third time. In order that the program will not keep executing despite the wrong password, you need to build in another if statement. You’ll find the following script in the file pass3.htm: var password, i=0; while(password!="knowware" && i<3) { password=prompt("Enter the password!",""); i++; } if (password=="knowware") { location.href="target.htm"; } else { alert("The password is incorrect!"); }

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Functions and Event Handlers

19

JavaScript Functions and Event Handlers OK, what now? Functions? Are we using a spreadsheet?

Event Handler

Event reacted to

onLoad

Loading of an object (graphic, page)

No! But functions can make a script much more flexible. For all of our programs thus far have one decisive flaw: they start at the moment when the HTML document is loaded. And we’ll change that now!

onAbort

Abortive loading of an object

onClick

Clicking an object (button)

onDblclick

Double-clicking an object

onMouseover

Passing the mouse cursor over an object (graphic)

Imagine a function that serves as a “container” for several commands. These can be bundled quickly and held together in brackets (yes, yes, the curly kind {} ).

onMouseout

Moving the cursor away from an object

onFocus

Object becomes the active object

onChange

Object (form contents) is changed

onSelect

Object (text) is selected

Defining a Function

onBlur

Object is left

onSubmit

Form contents sent

onReset

Form contents reset (erased)

onUnLoad

User leaves the window

onError

Script error

To define a function, all you need is the keyword function. After that, type in a name of your own choosing for the function. This line must conclude with a pair of round brackets (parentheses). In function names, you can use numbers and even the underscore character (_). JavaScript differentiates between capital and lower-case letters. Avoid umlauts and strange characters like %, &, ?, @ <, >, etc. You are not allowed to use reserved words (while, if, break, else, function, return, true, this, var, etc.) as function names. The general syntax looks like this: function name() { Code lines }

Let’s create a simple function that will change the background color to silver.

Starting with Buttons You’d like to call the function when the user clicks on a button? The syntax for such a button looks like this:


A button must be designated as a form
. For value, you need to enter the text on the button. Place the function name in the quotation marks next to onClick=.

function silver() { document.bgColor="silver"; }

The fact that the function name and the color name correspond here is pure accident. Only the brackets are mandatory! If you now call up your document with the function, at first you’ll notice…nothing at all. The browser doesn’t respond to this command at all – or does it? A function only starts when you call it! For this you’ll need the event handlers.

Event Handlers Event handlers make working with JavaScript very flexible and exciting! Events include clicking a button (onClick), passing the mouse pointer over a graphic (onMouseover), or the loading of a document (onLoad). (Non-events, by contrast, are authors’ royalties; these are sooner dramas!) You’ll see the most important event handlers in the following table:

For this example, you’ll need to add the following three lines to the HTML document: 1 2 3



When the button is clicked, the background color changes to silver – even in Netscape! You’ll find the result in the functions folder in the file silver.htm.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Functions and Event Handlers

20

How Can I Call Functions? Since functions are such a big deal, I’ll show you the most popular ways to call them. So then: off to our next event!

onClick: calling functions with a button You’re already familiar with this option. A button is probably the fastest way to call a function.


onLoad/onUnLoad: calling functions when loading or leaving a document Just as interesting is the possibility of “triggering” a function when loading a document. To do this, add the onLoad event handler to the tag.

Of course you can also call a function with onUnLoad when leaving a document. But if you’re changing colors, this doesn’t make much sense. But perhaps for an alert() box that bids the surfer goodbye?

onMouseOver: calling functions when passing over an object You’d like to “fire up” the function when the mouse passes over a graphic? At least in Internet Explorer, this looks like this:

Even a title or block of text can be “made sharp” in this way, at least in Internet Explorer:

Hey there!

I am the touchy title!



But unfortunately, the Netscape browser isn’t as cooperative. You’d like to make a graphic “sensitive” here? That only works with a trick: just include onMouseover in a hyperlink that includes a graphic. Since the event handler springs right into action, it doesn’t matter to what the link refers. Try this:

Calling a function with a hyperlink The last variant works alike in all browsers. Just incorporate the function into a simple text hyperlink that calls the function. Just clickhere!

The document fstart.htm in the functions folder contains many possibilities for calling exemplary functions. Here’s an overview of the complete source code: Function <script language="JavaScript" type="text/javascript">

Document with Function

Scotch tape

To start the function, please click here!



© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Functions and Event Handlers

21

Function with Parameters Back to the color function from the first example. You’d like the surfer to be able to choose from among several background colors? Then you could write a function for each color. Using a button, you could call an individual function. I wish you much fun creating this script. Whoever doesn’t have any work makes some for him- or herself. But this is much too tiresome for me. It would be much more practical and flexible to pass a single parameter to a function so that it can go on its merry way. Then you’d just need to place a variable in the parentheses. The syntax looks like this: function Name(Variable)

In the document itself you could then assign our nice little variable any value, for our example naturally a color name. Disguised as a function, this even works in Netscape 4.x!

Here’s the complete document parameter.htm in brief: Function with Passed Parameter <script language="JavaScript" type="text/javascript">

Function with Passed Parameter



Is it clear to you how this example works? The function background contains the parameter color. Each selection button has a different value. This represents one of the allowed color names, for example yellow. If you click the second button, the value yellow is passed. And the line document.bgColor=yellow takes care of producing the desired background color.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

JavaScript Inline and External

22

JavaScript Inline and External: Navigation Buttons and Links Are you familiar with inline scripts? These are little script snippets that you can place into your HTML document without a lot of fuss. No inconvenient <script> tags, no comment characters, no variables, decision-making structures, or switch commands. Just like inline skating, inline scripts are truly a fine thing. You can make a lot of progress without much fuss. But you can’t do everything with them, otherwise you’ll „fall over.“

Hyperlinks with JavaScript You’re already familiar with normal hyperlinks. The following link refers to KnowWare: KnowWare

Try placing such a link on a button! It’s very easy – with inline JavaScript. Don’t forget that buttons must be placed in
tags. Furthermore: if you’re nesting quotation marks, the inner quotation marks must be apostrophes (‘).




After clicking on the appropriate button, the contents of the browser window will be replaced with those of the new page.

Using this method, you can also open a new browser window. Then, instead of using location.href, you’d use the window.open() method. Here’s what a complete script for a button looks like: .

The history Object With the history object, you offer the surfer the opportunity to navigate forwards and backwards. The methods required for this are called back() and forward(). Here an inline script will also do the job. Or you’d like to offer a simple text link backwards or forwards? That would look like this: back forwards

Of course you can also use a button to accomplish this. Just write:


You’ll find examples of this in the file history.htm in the functions folder.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

JavaScript Inline and External

23

Storing JavaScripts as Separate Files Since we’re already talking about inline scripts with such enthusiasm, we should turn our attention to another interesting possibility: you can also store JavaScript files externally! You can pack the whole code mess into its own file, give it a nice name, and the file extension .js. Very important: omit all comment characters and <script> tags in the external text file! And finally, you’ll need to put just one reference to the cool JavaScript file into your actual HTML document. Place it exactly where you’ve been writing the scripts, namely right under and above . Here’s the pattern: <script src="filename.js" language="JavaScript" type="text/javascript">

Let’s take an example. Do you still remember the super-secure password protection program from before? Just pack the code into an external text file. You could call this file password.js, for example. In addition, I’ve put the whole thing into a function called pwcheck().

password.js Now I’ll show you the complete source code for the stored password file password.js. Here’s a tip: when saving the file, use the quotation mark trick so that the ending is forced to be .js. function pwcheck() { var password, i=0; while(password!="knowware" && i<3) { passwort=prompt("Please enter the password!",""); i++; } if (password=="knowware") { location.href="target.htm"; } else { alert("The password is incorrect!"); } }

passcheck.htm The actual HTML file, by contrast, look like this. Notice the call of the external JavaScript file in the fourth line. External Password Protection <script src="password.js" language="JavaScript" type="text/javascript">

Do you know the password?



You’ll also find the complete example with passcheck.htm and password.js in the folder functions. The corresponding HTML file is called, as mentioned above, passcheck.htm. Please note that saved JavaScripts work only with Internet Explorer 4 and Netscape Navigator 3 and above. But this isn’t so bad; most surfers far exceed these minimum requirements.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

JavaScript Windows

24

Programming Your Own Windows with JavaScript Have you already admired them? On some pages, nice little popup windows appear, without bothersome buttons and in a handy size. Sometimes you’ll find a graphic here. In many cases, however, these contain complete HTML documents.

Syntax for a JavaScript window To create such a window, you’ll need to use the open method of the window object, in particular, window.open(). Write the whole thing using the following syntax: window.open("Contents","Name","height=Pixel,width=Pixel,left=Pixel,top=Pixel")

With Contents I mean the page or graphic to be displayed. The Name can be choosen freely; for our purposes, it’s not important. The commands height and width determine the height and width of the window. With left and top, by contrast, you define the distance from the top and right edges of the screen. You can also omit left and top. Watch the placement of commas and quotation marks; here this is very important. Without an example, all of this doesn’t make much sense. Therefore I’ll show you a complete HTML document in which there are two windows. Just have a look at the file window.htm in the windows folder. First to the document that will be displayed. On the one hand, this is a GIF graphic of 100 x 143 pixels. In the example, it’s called outlook.gif. For this file I need a window that’s one pixel larger. I decided upon 115 x 160. The second document is a simple HTML document that contains text. The name of the document is critique.htm. This window should be 250 x 350 pixels. This will suffice to display the contents.

Source code for the document And what should the source code for the document look like? Have a look. This time I’ll show you the whole document: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

Creating JavaScript Windows <script language="JavaScript" type="text/javascript">
win.setTimeout("window.close()",20000); } //-->

Fenster in JavaScript

Book about Outlook

Reader criticism about the book



In Line 6 I’ve defined a function for the first window; it’s called window1(). The window itself is saved in a variable that I’ve called win. (The variable for the second window is also called win. But this isn’t a bad thing since these variables are both local variables that won’t outlive the function itself. So I can give two variables the same name.)

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

JavaScript Windows

25

In Line 8 I finally define the contents of the window; here it’s the graphic outlook.gif. The second function is concerned with the second window. The window itself is defined in Line 12. In addition, I’ve added resizable=yes. This is how you can specify that the window’s size can be changed. In Lines 20 and 21, the hyperlinks with inline JavaScript take care of opening this window.

Closing windows automatically and manually After a while, you’ll find that there are too many JavaScript windows on the screen. And of course you can’t expect the surfer to close all the windows in an orderly manner. Close your windows. You can do this automatically or manually. I’ve built the automatic method into our window script above. For example, the second window will close automatically after 20 seconds. Line 13 takes care of this with the aforementioned setTimeout() method. But what do you do if you want to close windows manually? It’s easy! At the very least, you can do this with HTML documents that are displayed in JavaScript windows. Here you should use the close() method. For example, you could write in the source code of the window to be displayed: Close window

Of course you could also program a close button:


You’ll find an example of this in the file windowclose.htm.

Windows as Remote Control Objects Now you’re a real window expert! And now I’ll show you the trick for expanding a little JavaScript window to make a real remote control. To do this you’ll need the window object again, this time also the opener property. This property refers to the window that really opened the current window, that is, to the opener. In the example we’re concerned with three pages, pagea.htm, pageb.htm, and pagec.htm. The remote control window is called directly from pagea.htm. Build the following script into pagea.htm. Since we’re only talking about one window, you won’t need a function or a hyperlink or a button to open it. <script language="JavaScript" type="text/javascript">

But surely you’re eager to get to know the source code for the „remote control.“ In the example, it’s in the document rc.htm. rc stands for remote control!

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

JavaScript Windows

26

An overview of the source code Here’s an overview of the complete „remote control“ document: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Remote Control <script language="JavaScript" type="text/javascript">

Remote Control

Page A
Page B
Page C


And now we’ll have a closer look at the script for the remote control: Look at Line 7. First you determine that this is a function that gets a parameter passed to it. You just need to place the appropriate parameter (that is, the variable) in parentheses. I’ve called the variable target in the example. The function itself is called reference(); with parameters, the whole thing reads reference(target). And now have a look at Line 8. Here we’re talking about the opener property of the window object. This property refers to the previous window, that is, to the opener. And in this „opener,“ the document that is referred to by the variable target is now displayed. But what is returned by the variable target? That’s easy. It depends on which of the three JavaScript hyperlinks (Lines 15-17) you click on now. Line 16, for example, provides the string pageb.htm to the variable target. The function is called and opens the file pageb.htm in the original window. I’m only saying: pass parameters! It’s a wonderful thing! And by the way: you’ll find all the exemplary documents for the remote control in the windows folder.

Creating Windows „On the Fly“ Back to normal JavaScript windows. The opportunity to create such a window „on the fly“ is particularly slick. In this case you don’t need to prepare any individual HTML file for the window. Using the method document.write, you can write directly into this window. And how do you do that? Take the familiar syntax. But leave the space between the quotation marks intended for the window contents blank: window.open("","Name","height=Pixel,width=Pixel,left=Pixel,top=Pixel")

Of course you must also create a variable in this situation. Then you can write into the window. var win win=window.open("","Name","height=Pixel,width=Pixel,left=Pixel,top=Pixel") win.document.write("Title<\/title><\/head><body>Contents<\/body><\/html>") win.document.close();<br /> <br /> Use the familiar HTML tags. The only peculiarity of document.write() is: end tags must contain a backslash before the slash. The writing in the window must end with document.close(). There’s an example with further commentary on the page after the next one.<br /> <br /> © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01<br /> <br /> Reading Out Information Using the screen Object<br /> <br /> 27<br /> <br /> Extracting Information from the Surfer and Reacting to it JavaScript allows you to extract some interesting properties from the surfer’s browser window. It doesn’t matter what the screen resolution, browser type, or color depth is: you can access all that information.<br /> <br /> The screen Object The so-called screen object is on center stage here: Property<br /> <br /> returns<br /> <br /> Example of output<br /> <br /> screen.height<br /> <br /> Height of the screen in pixels<br /> <br /> 600 or 768, etc.<br /> <br /> screen.width<br /> <br /> Width of the screen in pixels<br /> <br /> 800 or 1024<br /> <br /> screen.availHeight<br /> <br /> Visible screen height in pixels<br /> <br /> 572 or 740<br /> <br /> screen.availWidth<br /> <br /> Visible screen width in pixels<br /> <br /> 780 or 1010<br /> <br /> screen.colorDepth<br /> <br /> Color depth<br /> <br /> 8, 16, or 32<br /> <br /> navigator.platform<br /> <br /> Operating system<br /> <br /> Win32 or MacPPC<br /> <br /> navigator.appName<br /> <br /> Browser name<br /> <br /> Microsoft Internet Explorer or Netscape<br /> <br /> navigator.userAgent<br /> <br /> Exact browser designation<br /> <br /> Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)<br /> <br /> navigator.language<br /> <br /> Language<br /> <br /> de, en, es (Spanish), fr (French), da (Danish), etc. Only works with Netscape 4 and above, not with Internet Explorer!<br /> <br /> And what can you do with this? Read out the information and react to it. The best-known example is the famous „Browser Question.“<br /> <br /> Netscape or Internet Explorer? The Browser Question! It’s really annoying: each browser represents your document a little differently. Precisely the differences between Internet Explorer and Netscape are really quite great. If you want to be really professional about things, you’ll just create two pages: one for Internet Explorer and one for the Netscape browser. On the pre-switching page, you’ll determine the surfer’s browser type and create a corresponding redirection! The surfer won’t even notice that they’re being redirected since everything moves so fast! Here’s the source code for the pre-switching page. Let’s use the familiar switch command for this example: var browser; browser=navigator.appName; switch(browser) { case "Microsoft Internet Explorer": location.href="iepage.htm"; break; case "Netscape": location.href="netpage.htm"; break; default: alert("Unfortunately you don’t have the right browser for our pages!"); }<br /> <br /> If the surfer „browses in“ with Internet Explorer, they’ll be redirected to the page iepage.htm. Netscape users land on netpage.htm. Compare this with the file browserquestion.htm in the screen folder. Here’s a curiosity: the browser Opera 4 identifies itself internally as „Netscape“ and so the visitor will be redirected to the Netscape page. But that’s not all: this way you can also read out the screen resolution and react to it. Unfortunately the output of the language (navigator.language) only works with the Netscape browser; see the last table entry. So in practice, it’s not much use.<br /> <br /> © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01<br /> <br /> 28<br /> <br /> Reading Out Information Using the screen Object<br /> <br /> Exercises for the screen object: creating windows „on the fly“ You’d like to create a window „on the fly“? Then have I got an exercise for you! Read out all the information that the screen object offers you. Put the whole thing in a table so you can get an overview. Do you remember how to create a table in HTML? It’s easy; I’ll show you the basics of how to create a table with border lines! A table begins with <table border="1"> and ends with </table>. The attribute border="1" takes care of the border lines. The individual lines are enclosed in the tags <tr></tr>. The tags <td></td> handle the definition of individual cells. That’s not so hard, or am I wrong? And this table should be presented to you in a new browser window, like this:<br /> <br /> Behind this stands the following source code. I’ll show you the whole document screen.htm this time, not just the JavaScript portion of it: 1 2 3 4 5 6 7 8 8 10 11 12 13 14 15 16 17 18 19<br /> <br /> <html> <head> <title>Seeking Information <script language="JavaScript" type="text/javascript"> Information<\/title><\/head>"); showwin.document.write("<body bgcolor='white'><table border='1'>"); showwin.document.write("<tr><td>Screen height<\/td><td>" + high + " Pixel<\/td><\/tr>"); showwin.document.write("<tr><td>Screen width<\/td><td>" + wide + " Pixel<\/td><\/tr>");<br /> <br /> © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01<br /> <br /> Reading Out Information Using the screen Object 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36<br /> <br /> 29<br /> <br /> showwin.document.write("<tr><td>Color depth<\/td><td>" + color + " Bit<\/td><\/tr>"); showwin.document.write("<tr><td>Operating system<\/td><td>" + os + "<\/td><\/tr>"); showwin.document.write("<tr><td>Browser<\/td><td>" + name +"<\/td><\/tr>"); showwin.document.write("<tr><td>Exact designation<\/td><td>" + browser +"<\/td><\/tr>"); showwin.document.write("<tr><td>Language (only Netscape)<\/td><td>" + language +"<\/td><\/tr><\/table>"); showwin.document.write("<p><a href='javascript:window.close()' rel="nofollow">Window close<\/a><\/p>"); showwin.document.write("<\/body><\/html>"); showwin.document.close(); } //--> </script> </head> <body bgcolor="white"> <h1>Seeking Information</h1> <form><input type="button" value="Information about your system" onclick="info()"></form> </body> </html><br /> <br /> It looks more complicated than it is. First, the individual properties of the screen object are saved to variables (Lines 8-14). In Line 15, you’ll create the window showwin. I thought of this name all by myself. You should leave the actual contents of the window free for the moment; after this, put a comma and enter the name of the window to be opened ("","showwin",...) Then, as usual, you should determine the width and height of the window. The window in the example is 430 pixels wide and 310 pixels high ("width=430,height=310"). With document.write (or here, showwin.document.write, since you’re writing directly to the window), you’ll create the HTML document in a new window. Here you should write a complete document with a header and body. In Line 16, for example, you’ll see the header of the HTML document. The <body> tag follows in Line 17. In addition, I’m already starting the table with <table border='1'>. Did you notice that I enclosed the attributes in apostrophes rather than in quotation marks? This is because the HTML tags are already enclosed in quotation marks. And when you’re nesting quotation marks in JavaScript, the inner quotation marks must be apostrophes. If you don’t follow this rule, you’ll find that you get error messages. As I’ve already mentioned: if you use HTML tags within document.write(), you should use the extra backslash in the end tag. So, for example, write <\/title> etc. <\/head> instead of or . This serves to mask the „slash special character.“ In case this way of writing is too complicated for you, you can go ahead and use the usual methods. They will work anyway. In Line 25 you’ll find a hyperlink that will close the window. Line 26 contains the closing HTML tags and Line 27 closes the document.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Random Numbers and Mathematics

30

Some Mathematics: Random Numbers with the Math Object Did you know that in mathematics, I’m an absolute zero? I’ve been pulling the wool over your eyes when I’m writing about functions, counters, and calculations about which I know nearly nothing. (But to this point nobody has noticed this, not even in my two Excel books!)

Script for the Dice Game First, the result: this is what the complete HTML document for our dice game looks like in the browser:

Nevertheless, I repeat: I don’t know anything about what I’m writing about! In this spirit I’m going to show you how to program a dice game with JavaScript. On the next page, we’ll extend this example into a script, which references “random links.” And all of this just to show you about arrays. Is everything clear? No? Then come along anyway!

The Math Object Just to aggravate us, the inventors of JavaScript thought up the math object. And math possesses some truly ghastly methods that remind me of Excel. But don’t despair – for our example we’ll only need two methods.

Math.round This command rounds a number according to the mathematical rule: if the digit after the decimal point is larger than 5, you round up. Otherwise, you round down. Math.round(1.5), for example, would produce a result of 2.

Math.random This handy command “thinks up” a random number between 0 and 1. You’d like to create another random number? Then try using this formula: Math.random()*(b-a)+a

Here a is the smallest and b the largest possible number. For our dice game, the formula should look like this: Math.random()*(6-1)+1

And since this equation can still produce warped values, you need to round things out with math.round. Let’s go ahead and try this with a variable: var random; random=Math.random()*(6-1)+1; random=Math.round(random);

Do you understand all of this? Not yet? Then try it out with a practical example. Whip out your editor and type along!

We’ll build a function called randomnumber(), call this function using a button, and display the number in a smart alert() box: Dice Game <script language="JavaScript" type="text/javascript">

The Dice Game:



When you’re copying the script, please watch that the line for the button doesn’t get broken up. If you wish, you can compare this script with the file randomnumber.htm in the arrays folder. And now nothing stands between you and your “modern dice game” with JavaScript. Of course you can also customize this script to suit your needs. How would it be as a decision-making tool in your search for the right lotto numbers? In the course of this booklet, I’ll no doubt have more ideas!

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Arrays: Random Links and Jukebox

31

More Fun with Arrays: Random Links and a Jukebox Since we’re already talking about things random, we can go ahead and create a script for random links. You already know how a JavaScript link is programmed. And we’ve just seen how random numbers work. So with an if command…or switch…only a given number of variables…

An Overview of Arrays Stop! Before you get too far, let me present arrays to you. These are refined data fields that can save several values at one time. Instead of 100 or 6 variables, you just need one. Then you can address the individual values using their respective indices. I’ll show you the syntax for such an array using the example of Web addresses: var address; address=new Array(6); address[0]="http://www.knowwareglobal.com"; address[1]="http://www.jchanke.de"; address[2]="http://www.maddocs.com"; address[3]="http://www.google.com"; address[4]="http://www.yahoo.com"; address[5]="http://www.downloads.com ";

First we assign our variable (here address) as an instance of the array object. You do this by using the keyword new Array. The number in parentheses after Array specifies the number of elements in the array; this number is “optional.” So far so good. In the lines below, we assign the individual values, here our Web addresses. These are text strings, therefore you must place them in quotation marks. Place the corresponding index value in square brackets. Make sure that your arrays always begin with an index value of 0! The entry address[5] stands for the sixth value. You wouldn’t be the first person to miscount here. So remember: arrays begin counting with 0!

The Script for the Random Links And now here’s the JavaScript code. Watch out; this time we don’t need an alert() box, but we do need a random number between 0 and 5. The last line takes care of the “randomly-selected” Web address: function randomaddress() { var random=Math.random()*(5-0)+0; random=Math.round(random); address=new Array(6); address[0]="http://www.knowwareglobal.com"; address[1]="http://www.jchanke.de"; address[2]="http://www.maddocs.com"; address[3]="http://www.google.com"; address[4]="http://www.yahoo.com"; address[5]="http://www.downloads.com"; location.href=address[random]; }

In the HTML document, you can call the function with a button or a JavaScript link: Please click here.

Compare this with the file randomlink.htm in the arrays folder.

Abbreviation Before we get to the next script, I’ll show you quickly how to abbreviate when working with arrays. Place all values directly in parentheses after newArray. You don’t have to provide the total number. This is assuming that you’d like to save all the weekdays in one array. You could do this as follows: var day; day=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

Here the “index rule” applies too. With day[0], you’ll get a value of Sunday, day[2] would be Tuesday. More about this later on.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

32

Arrays: Random Links and Jukebox

Programming a Jukebox How would you like to have a jukebox? Just incorporate the sound files and call them up with JavaScript. In the example, you can play a song by clicking a button. In JavaScript, you refer to sound files just as you do in HTML. Using href, you place a link in the appropriate place. With location.href=songname, you call the piece and – if you’ve got a playback program on hand – it will be played. It doesn’t matter whether the object in question is a WAV file, an AVI film clip, a MIDI piece or a MP3 file. Here’s an overview of the example. I’ve called it jukebox.htm and stored it in the arrays folder. The first three buttons each play back a different MIDI file. The random button “seeks out” one of the three songs for you. I’ll list the entire source code so you’ll have an overview of it: Calling up Songs with Functions <script language="JavaScript" type="text/javascript">

Play back Song



The principle of this is easy to understand. We’re working with an array (we’ve used the abbreviated address form), which stores our three songs and assigns them index numbers 0 to 2. The function playsong() picks out a particular song based on the value that’s passed to the parameter, then that song is played back by the code location.href=song[songnr]. Make sure that the variable song in the example is a global variable so that its value will be available to all the functions in the script. This is why we don’t place the array itself in a function. The fourth button refers to the function random(), which creates a value between 0 and 2 and plays back the corrsponding file.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

Date Object: Date and Time

33

Reading Out and Displaying the Date and Time Especially interesting is how to work with dates and times. Read out on what day a surfer visited your site or what time he came. React to this.

The date object In JavaScript you’ll use the so-called date object. With it, you can easily read out the date and time. Here’s a quick overview of the methods of this marvelous object: Method

Explanation

Example

getDate()

returns the day of the month as a number from 1-31

myDate.getDate()

getDay()

returns the weekday as a number from 0 to 6, whereby the counting begins with 0=Sunday. Thus Friday would be a 5.

myDate.getDay()

getMonth()

returns the month as a number between 0 and 11, whereby the counting begins with 0=January. Thus May is 4, not 5.

myDate.getMonth()

getYear()

returns the number of the year

myDate.getYear()

getFullYear()

returns the number of the year as a four-digit number

myDate.getFullYear()

toGMTString()

the date is transformed into a string that corresponds to the so-called IETF standard. Thus November 21, 2000 comes out as Tue, 21 Nov 2000 12:24:23 UTC.

myDate.toGMTString()

getHours()

returns the hours

myDate.getHours()

getMinutes()

returns the minutes

myDate.getMinutes()

getSeconds()

returns the seconds

myDate.getSeconds()

Let’s try out our new knowledge with a practical example. Return, for example, the date, including the weekday and day of the month. Display it in an alert() box. To do this, you’ll need to create a new instance of the date object. Use the keyword new to do this.

Surely the rest is not hard. Here’s the first script; compare it with date.htm in the date folder. var myDate, date, day, month, year; myDate=new Date; date=myDate.getDate(); day=myDate.getDay(); month=myDate.getMonth(); year=myDate.getFullYear(); alert("Date: " + date + ", Day: " + day + ", Month: " +

month + ", Year: " + year);

The next script displays the date and time in a window created “on the fly.” Surely by now you can deduce for yourself how the function works. Since the hours and minutes don’t have any leading zeros in JavaScript, we’ll add these with an if statement and string operators. The time display is static. With setTimeout(“datewindow()”,10000); you can transform the script so that the display will be updated every 10 seconds. But then after closing, the window will “pop up” again 10 seconds later.

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

34

Date Object: Date and Time

And here’s the corresponding source code. You’ll also find it in the file datewindow.htm. You’ll find the slightly transformed “dynamic” version, by contrast, in the file dynamicdate.htm. Both of these files are in the date folder. Date Window <script language="JavaScript" type="text/javascript"> Date and Time<\/title><\/head><body>"); datewin.document.write("<b>Today is " + weekday[day] + " " + monthname[month] + " " + date + ", " + year + "!"); datewin.document.write("<br \/>It is exactly " + hour + ":" + minute + " O’Clock.<\/b>"); datewin.document.write("<form><input type='button' value='OK' onClick='window.close()'><\/form>"); datewin.document.write("<\/body><\/html>"); datewin.document.close(); } //--> </script> <h1>Date Window</h1> <form><input type="button" value="Display Date and Time"onclick="datewindow()"></form> </body> </html><br /> <br /> I hereby invite you to experiment more with the date and time. So much for now: for a dynamic display, you’re best to use a text field or the status line!<br /> <br /> © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01<br /> <br /> HTML and XHTML Reference<br /> <br /> 35<br /> <br /> XHTML Reference: The Most Important Commands: On the next pages I’ll show you the most important (X)HTML commands with explanations. When it makes sense, I’ve included an example in the right-hand column. If the tag possesses an internal slash (<meta />), this means that the tag must be turned off internally. But this only matters if you really want to follow the XHTML standard.<br /> <br /> General Tags In this table you’ll find the best-known general HTML tags and their most important attributes. As a reminder, I’ll show you the basic structure for an HTML page right up front. Don’t forget: every tag needs an end tag. HTML and XHTML documents must have a file extension of htm or html. <html> <head> <title>Page Title, appears in the title line of the Browser Contents

I’m not going to cover the <meta> tags here since I covered them at length in the beginners’ booklet. Also, they are only noticed by a very few search engines. The German search engine Fireball (www.fireball.de), for example, has a meta tag generator. Tags

Attributes

Possible Values

Explanation

Example



defines an HTML file



defines the header



My First Page creates the title of the file, which appears in the title line of the browser

<meta />

creates a space for additional information



<meta name="author" content="Peter Pan" />

introduces the main area text

hex. Code, color name

background

defines text color



adds background graphics



bgcolor

hex. Code, color name

defines a background color



link

hex. Code, color name

link color



alink

hex. Code, color name

color of active links



vlink

hex. Code, color name

color of visited links



Paragraphs, Line Breaks, and
The following table shows you how you can create paragraphs (

) and line breaks (
). Particularly interesting is the
container, which you can use to shape a page freely with the help of style sheets. You can use
instead of

if you wish. Tags

Attributes

Possible Values

align

left, center, right, justify

class or id

free name



Explanation

Example

defines a paragraph

This is a paragraph



alignment

This is a right-aligned paragraph



defines your own class

This is a quotation






line break



“container” on the paragraph level

This is a freeform paragraph


defines your own class

A Division


class or id

free name

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

HTML and XHTML Reference

36

Tags for Simple Text Formatting In HTML you place the passages you’d like to format between pairs of pointy brackets, the familiar tags. There are countless numbers of formatting symbols. Here are the most important ones in overview: Tags

Explanation

Example

to


heading levels 1 to 6

Header 3





bold

This is a bold statement.



italics

With italics everything looks slanted!



underlined

Do not use any more underlining.

<strong>

strong, strongly emphasized, most often in bold

Don’t come on too <strong>strong.



used for computer source code

function hello()



text that must be entered using the keyboard

Just type md knowware.



citations, most often in italics

see also Maardt 97.



definition, definition text

p stands for paragraph

<samp>

text is output the way it’s input

<samp>§%&$



used for short citations, most often in italics

Hello she said.



teletype, non-proportional font

Most text is in Courier

<span><span>

defines a <span> container; these are ideal for formatting characters with style sheets (CSS)

This is a <span class="red" id="red">red word.

<strike>

strikethrough

<strike>strikethrough



large font, useful for emphasis

Once upon a time.

<small>

small font

<small>always small

<sub>

subscript

H<sub>2O

<sup>

superscript

10<sup>5

<em>

emphatic, most often in italics

It is <em>really important!

Adding Graphics Files I’ve already explained in some detail in the beginners’ booklet how to add graphics to your documents. But once again, here are the most important rules, since mistakes always crop up: only the GIF, JPEG or PNG formats are allowed! The file names can’t contain umlauts or empty spaces. Pay attention to capitalization (or lack thereof). A reference to won’t work if the graphic itself is called Tower.gif! Unix systems, in contrast to Windows systems, distinguish between upper- and lower-case letters! The graphics must either be in the same folder as the HTML file or the reference to the subfolder must be placed correctly. Absolute path names like C:\My Documents\tower.gif are forbidden! Tags

Attributes

Possible Values

src

source of the file



left

left-aligned with the text flow



right

right-aligned with the text flow



width

pixels

width of the graphic

width="100"

height

pixels

height of the graphic

width="100" height="20"

alt

Text

alternative text, becomes Quickinfo

My House

border

pixels

adds a border (border=”0” is without)



vspace

pixels

additional space above and below

vspace="4"

hspace

pixels

additional space left and right

hspace="5"



Explanation

Example

adds a graphic file

align

alignment of the graphic

© Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

HTML and XHTML Reference

37

Drawing Lines With lines, you can loosen up your document. You can control the alignment, width, color, and thickness of the lines. Since the line tag
doesn’t have an end tag, it’s turned off internally in XHTML. Tags

Attributes

Possible Values

Explanation

Example

size

pixels

creates a line




thickness of the line; default is 1

width




pixels, %

width in pixels or percent; default is 100%




align

center

centered; default setting

left

left-aligned




right

right-aligned




color

hex. Code, color name

color, but only in Internet Explorer




noshade

noshade

line should have no shadow







Making Lists You can use the following tags to make nice-looking lists. You can select the various formats and start values for yourself. Tags

Attributes

Possible Values

Explanation

Example

type

disc

default setting; filled round bullets

square

creates filled square bullets



    circle

    creates hollow round bullets



      unordered list, creates a list with bullets



        ordered list, creates numbering

          type

          start

          1

          type of numbering; default is Arabic numbers

          A

          creates upper-case letters



            a

            creates lower-case letters



              I

              upper-case Roman numbers (capital i)



                i

                lower-case Roman numbers (lower-case i)



                  number

                  starting value; default is 1



                    list, single list entry

                  1. Cats


                  2. value




                    1. Font Tags Until recently, the tag was touted as a cure-all for formatting text. In the meantime, it’s been replaced by style sheets. The tag is no longer reliable in XHTML, but due to “compatibility considerations,” it’s still used. Finally, it also works with older browsers, something that one can’t say about style sheets. Tags

                      Attributes Values



                      Explanation

                      Example

                      sets font characteristics face

                      typeface

                      defines a typeface

                      Example

                      size

                      1 to 7 (Normal=4) or relative values like -1, -2, +1, +2 (Normal=0)

                      defines the font size

                      3 sizes larger

                      color

                      hex. value or color name

                      defines the font color

                      The Blue of the Sky

                      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

                      HTML and XHTML Reference

                      38

                      Adding Sound Files and Videos Here are several ways to incorporate media files into HTML. It doesn’t matter whether you’re talking about MIDI, WAV or MP3 sounds, or AVI or Quicktime film clips. The tag , which you can use to incorporate a background noise, is comfortable to use, but it’s only supported by Internet Explorer. This tag is no longer reliable in XHTML. The alternative is <embed>. The following example adds a sound file as background sound using <embed>. Width and height are intended merely as “placeholders”: <embed src="song.mid" width="150" height="40" autostart="true" loop="false" hidden="true" />

                      Warning: media files can also be incorporated using a link ! Tags

                      Attributes

                      Possible Values



                      Explanation

                      Example

                      plays back a sound file when a document is called up src

                      name of the only works in Internet Explorer; this sound file tag adheres to no official standard

                      src

                      filename

                      source of the file

                      <embed src="song.mid" />

                      width, height

                      pixels

                      height and width of the Player

                      <embed src="film.avi" width="150" height="75" />

                      autostart

                      true, false

                      determines whether the piece will be played back automatically

                      <embed src="song.mp3" autostart="false" />

                      loop

                      true, false

                      determines whether the sound will play back continuously;

                      <embed src="song.mp3" autostart="false" loop="false" />

                      hidden

                      true, false

                      determines whether the player will be displayed or hidden, for example, for background sounds

                      <embed src="song.mid" hidden="true" />

                      <embed />



                      incorporates a media file

                      Incorporating and Formatting Moving Text Who would have thought it: everything rolls, and I don’t mean just on inline skates! The tag <marquee> is a part of the official (X)HTML standard, even if it’s not supported by the Netscape browsers. Phooey! Tags

                      Attributes

                      Possible Values

                      <marquee> loop

                      numbers

                      behavior

                      Explanation

                      Example

                      defines moving text

                      <marquee>Everything rolls

                      number of repetitions; default is infinite

                      <marquee loop="5">Rolls 5x

                      defines the moving behavior scroll

                      default setting = simple movement

                      behavior="scroll"

                      alternate

                      rolls back and forth

                      behavior="alternate"

                      slide

                      rolls in and stays

                      behavior="slide"

                      direction

                      determines the direction left

                      default setting = from the left

                      direction="left"

                      right

                      from the right

                      direction="right"

                      down

                      downwards

                      direction="down"

                      up

                      upwards

                      direction="up"

                      bgcolor

                      hex. value or color name

                      background color for the moving text

                      bgcolor="yellow"

                      height

                      pixels, percent

                      height of the moving text

                      height="100"

                      width

                      pixels, percent

                      width of the moving text

                      width="20%"

                      scrollamount

                      numbers

                      determines by how many pixels the object will move with each animation step

                      scrollamount="25"

                      scrolldelay

                      in ms

                      duration of the pause between two animation steps in milliseconds

                      scrolldelay="1000"

                      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

                      HTML and XHTML Reference

                      39

                      Tags for Forms Forms are very important in HTML. This is how you can retrieve information from the surfer and send it to yourself. Either you can collect the information using a CGI program on the server (database) or send it to yourself via e-mail. But I’m sure you already know this. Here’s the basic format of a form that you can have sent to yourself via e-mail. Instead of email, put your own e-mail address in. With ?subject=subjectline you can even add a subject line. The attribute enctype="text/plain" ensures that you’ll receive the form’s contents directly in the body of the e-mail message and not as an attached file. I didn’t know the trick with enctype="text/plain" in the first two editions of the beginners’ booklet. The following form example contains a text input field with 3 lines and 50 characters per line. A line break is possible. You’ll get the contents of the form sent to your e-mail address.



                      And now here’s an overview of the tags, attributes, and values that you can use in forms. Tag

                      Attributes Values



                      Explanation contains a form

                      action

                      path to CGI script

                      action="http://www.xyz.com/cgi-bin/a.pl"

                      e-mail address method

                      post or get

                      type

                      action="mailto:[email protected]" type of transmission

                      method="post"

                      defines a form element text

                      text entry field



                      password

                      password entry field



                      radio

                      radio button (simple choice)



                      checkbox

                      checkbox (complex choice)



                      reset

                      reset button



                      submit

                      submit button (send)



                      button

                      button



                      hidden

                      hidden form field





                      multiple-line text entry field rows, cols

                      value

                      number of lines, length



                      wrap

                      soft

                      line breaks; unfortunately, the default is off (no breaks)



                      <select>

                      defines a selection field size



                      Example

                      value

                      defines the number of fields to be displayed; default is 1 (drop-down list)

                      <select name="choice" size="1">

                      selection field in <select> tag



                      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

                      HTML and XHTML Reference

                      40

                      Anchors and Hyperlinks I’ve already explained quite a bit about anchors and hyperlinks in the previous booklet. They are practically the alpha and omega of the whole “home page thing.” Don’t forget that you can even incorporate graphics and multimedia files into your documents this way. For example, nobody is stopping you from offering the surfer an MP3 file with My MP3-Song or an AVI film clip with a similar link. Tags

                      Attributes

                      Values

                      Explanation

                      Example



                      href

                      source of the file (URL)

                      refers to an internal or external file

                      ... ...

                      name or id

                      anchor name

                      refers to an internal anchor

                      ...

                      mailto:e-mailaddress

                      creates a simple e-mail link

                      Mail

                      anchor name

                      defines an internal anchor

                      ...

                      Tags for Tables Without tables, you’d be horribly lost on the World Wide Web. How, otherwise, could you create an exact layout? With invisible tables, of course. Here, first of all, the visible structure of an invisible table, which is 200 pixels wide and has no border lines. Warning: as of now, all tags must be closed.
      Cell 1Cell 2
      Cell 3Cell 4


      And here are the most important table tags in brief. Tags

      Attributes

      Values



      Example

      introduces a table border

      pixels

      defines borders; default = 0



      bgcolor

      hex. Value, color name

      background color



      align

      left, right

      alignment, only thus is textflow accomplished; default is without



      width

      pixels, %

      width absolute or relative



      cellpadding

      pixels

      space between edge of cell and cell contents; “padding”



      cellspacing

      pixels

      spacing between the individual fields; the “thickness of the wall”



      defines a “typical” cell



      width

      pixels, %

      width absolute or relative



      align

      left, center, right

      alignment; default is left



      valign

      top, middle, bottom

      vertical alignment; default is bottom



      bgcolor

      hex. value, color name

      background color



      colspan

      value

      defines over how many columns a cell reaches



      rowspan

      value

      defines over how many lines a cell reaches



      defines a cell in the table header







      Explanation

      see

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      HTML and XHTML Reference

      41

      Tags for Framesets With framesets you can divide your browser window into frames. The basic structure of a simple frameset looks like this: 1 2 3 4



      Line 1 determines the window division. Here there are columns. The left column is 150 pixels wide, the right column remains variable. Be aware that this frameset itself is only the “steering file.” All you do here is set up the window division. In the example, Lines 2 and 3 specify which documents should be displayed in which frame. In this case, the documents in question are navi.htm and main1.htm. The page navi.htm is displayed on the left, the page main1.htm, by contrast, on the right. In the example you’ll need three documents: the frameset and the two HTML files to be displayed in the windows! The following table gives you an overview of the most important tags and attributes that you’ll use with frames.

      Tags

      Attributes

      Values



      Example

      cols

      pixels, %, *

      divides the window into columns



      rows

      pixels, %, *

      divides the window into rows



      border

      pixels

      determines width of the border in pixels; frames are hidden with border="0". This tag is old, but at the moment, it’s still indispensable



      frameborder

      0, 1 (yes, no)

      determines whether borders should be displayed. Older browsers expect yes and no

      frameborder="1"

      bodercolor

      hex. Code, color name

      assigns the border a particular color



      src

      filename

      gives the source for the frame



      scrolling

      auto, yes, no

      determines whether scroll bars should be displayed or hidden



      noresize

      noresize

      prevents the resizing of the window by the user



      marginwidth

      pixels

      width of the margin between the right and left edges of the window



      marginheight

      pixels

      height of the margin between the upper and lower edges of the window



      contains an alternative description for browsers that are not frame-enabled

      <noframes>Sorry, your browser doesn’t do Frames



      <noframes>

      Explanation contains a frameset; don’t forget the end tags!

      displays a page in a frameset

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      CSS Attributes and Values

      42

      Style Sheets: The Most Important Attributes of CSS Here’s a reminder: with style sheets, you can determine the individual properties of a tag exactly and comfortably. You can place the style sheet commands internally between and or you can store them externally. The style sheet syntax resembles that of JavaScript; individual blocks are surrounded by curly brackets, multiple properties are separated by commas. Each line must end with a semicolon. The following style sheet changes the font of

      and

      (Line 3) and the typeface, size, and color of normal body text

      (Line 4). As you can see in Line 3, you can “work on” several tags at once (here we’ve changed

      and

      ). Just separate them with commas. 1 2 3 4 5 6

      <style type="text/css">

      External style sheets, by contrast, are stored as text files with the extension css. Here you’ll need to place a reference to the style sheet file somewhere, in our example, in Lines 3 and 4. If you call the external style sheet standard.css, the reference would look like this in the HTML file: .

      Attributes for Changing Font Properties Attributes

      Values

      changes ...

      Example

      font-family

      fontname

      typeface

      font-family: Helvetica;

      serif

      typeface, with serifs

      font-family: Times, serif;

      sans-serif

      typeface, without serifs

      font-family: Arial, sans-serif;

      cursive

      typeface, cursive

      font-family: cursive;

      monospace

      typeface, non-proportional font

      font-family: monospace;

      fantasy

      typeface, fantasy font

      font-family: Western, fantasy;

      pt, cm, etc.

      font size

      font-size: 14pt;

      font-size font-style

      font-weight

      font style normal

      without properties

      italic

      italic

      font-style: italic;

      oblique

      oblique

      font-style: oblique;

      100 to 900

      thickness (measured in hundreths)

      font-weight: 500;

      normal

      corresponds to a value of 400

      font-weight: normal;

      bold

      corresponds to a value of 700

      font-weight: bold;

      font-variant

      font variants normal

      without properties

      small-caps

      small caps

      font-variant: small-caps;

      word-spacing

      pt, cm

      word spacing

      word-spacing: 5pt;

      letter-spacing

      pt, cm

      letter spacing (for block type)

      letter-spacing: 0,2cm;

      text-transform

      upper- and lower-case none

      remains unchanged

      uppercase

      capital (upper-case) letters

      text-transform: uppercase;

      lowercase

      small (lower-case) letters

      text-transform: lowercase;

      text-decoration

      emphasis none

      turns emphasis off

      text-decoration: none;

      underline

      underline

      text-decoration: underline;

      overline

      overline

      text-decoration: overline;

      line-through

      strikethrough

      text-decoration: line-through;

      blink

      blinking text

      text-decoration: blink;

      capitalize

      first letter in the word capitalized

      text-transform: capitalize;

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      CSS Attributes and Values

      43

      Attributes for Formatting Lists With style sheets, you have numerous options for formatting lists. Especially nice is, for example, the ability to use a small graphic as a bullet. The following line incorporates the file cross.gif as a bullet. But this file can be only a few pixels wide and high. ul { list-style-image: url(cross.gif); font-family: Arial, Helvetica; font-size: 14pt; }

      Here’s an overview of the most important possibilities: Attributes

      Values

      formats ...

      list-style-type

      Example

      appearance of lists

      (for ol)

      decimal

      default, (1, 2, 3, ...)

      lower-alpha

      lower-case letters (a, b, c, ...)

      ol { list-style-type: lower-alpha; }

      upper-alpha

      upper-case letters (A, B, C, ...)

      ol { list-style-type: upper-alpha; }

      lower-roman

      lower-case Roman numbers (i, ii, iii, ...)

      ol { list-style-type: lower-roman; }

      upper-roman

      upper-case Roman numbers (I, II, III, ...)

      ol { list-style-type: upper-roman; }

      disc

      default (filled circle)

      circle

      hollow circle

      ul { list-style-type: circle; }

      square

      square

      ul { list-style-type: square; }

      list-style-image

      url(filename)

      incorporates graphics as bullets

      ul { list-style-image: url(picture.gif); }

      list-style-position

      outside

      default, text is indented

      inside

      text remains justified on the left side, bullets are “integrated”

      (for ul)

      ol { list-style-position: inside; }

      Text Alignment Have a look at the next overview! Most interesting are the attributes text-align, text-indent, and line-height. Using these you can align paragraphs, control first line indentation, and line height. With line-height: 1.5, you’d create a space and a half spacing between lines. Watch out, you Europeans; decimal values in CSS are separated with dots (.), not commas. Attributes

      Value

      formats ...

      left

      left-aligned, default setting

      text-align: left;

      center

      centered

      text-align: center;

      right

      right-aligned

      text-align: right;

      justify

      justified (on both sides)

      text-align: justify;

      text-indent

      pt, cm, etc.

      first line indentation

      text-indent: 1cm;

      line-height

      pt, cm, etc.

      line height

      line-height: 14pt;

      relative value

      distance between lines is relative to the text size

      line-height: 1.2;

      text-align

      Example

      paragraph alignment

      vertical-align

      vertical alignment relative to the baseline on which the text is written baseline

      on the baseline, default setting

      vertical-align: baseline;

      super

      superscript

      vertical-align: super;

      top

      on top of the line

      vertical-align: top;

      text-top

      on top of the text

      vertical-align: text-top;

      middle

      middle

      vertical-align: middle;

      text-bottom

      below the text

      vertical-align: text-bottom;

      bottom

      below the line

      vertical-align: bottom;

      sub

      subscript

      vertical-align: sub;

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      CSS Attributes and Values

      44

      Formatting Borders and Frames Style sheets offer you a startling number of possibilities for formatting borders and frames. Unfortunately, many frame formats are not yet supported by popular browsers. The only browser I know of right now that can display all of the frame effects listed under border-style is Netscape Navigator 6.

      My tip: just try it out: Attributes

      Values

      formats ...

      margin

      pt, px, cm, etc.

      Example

      margin, outside “empty space”

      body { margin: 1cm; }

      margin-top

      margin from above

      p { margin-top: 10px; }

      margin-bottom

      margin from below

      h3 { margin-bottom: 3pt; }

      margin-left

      margin from left

      img { margin-left: 50px; }

      margin from right

      p.citation { margin-right: 10pt; }

      margin-right padding

      pt, px, cm, etc.

      inner space, filling or “padding”

      p { padding: 2cm; }

      padding-top

      padding from above

      body { padding-top: 15px; }

      padding-bottom

      padding from below

      h3 { padding-bottom: 1.3cm; }

      padding-left

      padding from left

      p.new { padding-left: 5px; }

      padding from right

      img { padding-right: 5cm; }

      border width

      p { border: 5px; }

      border-top

      border width above

      h1 { border-top: 0.2cm; }

      border-bottom

      border width below

      h2 { border-bottom: 4px; }

      border-left

      border width left

      p.citation { border-left: 5px; }

      border-right

      border width right

      pre { border-right: 12px; }

      border-style

      border style

      padding-right border

      px, cm, etc.

      solid

      solid (non-dotted) line

      p { border-style: solid; }

      double

      double borderline

      h1 { border-style: double; }

      groove

      3D effect with a “groove”

      p { border-style: groove; }

      ridge

      3D effect with a “ridge”

      p.neu { border-style: ridge; }

      inset

      3D effect with “inlaid” contents

      div { border-style: inset; }

      outset

      3D effect with contents “in relief”

      span { border-style: outset; }

      dotted

      dotted line

      h2, h3 { border-style: dotted; }

      dashed

      dashed line

      pre { border-style: dashed; }

      border-top-style

      see above

      border style only on top

      border-style-top: ridge;

      border-bottom-style

      see above

      border style only on bottom

      border-left-style

      see above

      border style only on left

      border-right-style

      see above

      border style only on right

      border-width

      px, cm, etc.

      distance between borderlines (border width), also possible here: border-width-top, etc.



      border-color

      hex. value, Name, rgb

      border color also possible here: border-color-top, etc.

      p { border: 7px; border-color: rgb(255, 0, 0); }

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      CSS Attributes and Values

      45

      Color and Background Graphics In the following table, surely color (element color) and background (background color) are the most interesting! You’d like to create a paragraph of text that’s on a yellow background? Then just define an individual class for the paragraph and name it something like yellow.

      This is a paragraph on a yellow background.



      In the style sheet itself, you can address this class as follows. Here too you need to use the “dot notation”: p.yellow { background-color: yellow; }

      In addition, you’ll find various ways in CSS to incorporate background graphics. Attributes

      Values

      formats ...

      Example

      color

      hex. value or color name

      color of an element’s contents, as a rule, text

      body { color: blue; }

      background

      hex. value or color name

      background color, for example, for a “shadow effect”

      h1, h2 { background: silver; }

      background-image url(graphicname)

      incorporates background graphics

      body { background-image: url(picture.gif); }

      backgroundrepeat

      determines how the graphic should be aligned repeat

      default setting; tiled

      background-repeat: repeat;

      repeat-x

      repeat only horizontally “on the x-axis”

      background-repeat: repeat-x;

      repeat-y

      repeat only vertically “on the y-axis”

      background-repeat: repeat-y;

      no-repeat

      no repetition

      background-repeat: no-repeat;

      backgroundattachment

      determines whether background graphics will move when scrolling

      backgroundposition

      scroll

      default setting; browser moves the background graphics when scrolling

      background-attachement: scroll;

      fixed

      background graphic remains stationery

      background-attachement: fixed;

      px, cm, etc.

      position of the background graphic, first left, then top

      background-position: 100px 10px

      Absolute Positioning (Important for DHTML) The biggest hit of CSS: you can place elements (text, graphics, etc.) absolutely on the page. The best thing to do is to pack the elements in
      containers, that is, “empty” tags on the paragraph level. You’d like to place text exactly 50 pixels from the top and 100 pixels from the left? Then write: div { position: absolute; top: 50px; left: 100px; }

      In the HTML document itself, you just need to use these
      tags.
      I am quite exactly placed


      Here’s an overview: Attributes

      Values

      position

      formats ...

      Example

      positioning on the page static

      default setting; normal positioning “in context”

      absolute

      absolute positioning with respect to the upper left-hand corner

      position: absolute; top: 10px; left 20px; position: relative; top: 20px;

      relative

      enables positioning relative to an existing element

      top

      px, pt ...

      distance from top edge

      left

      px, pt ...

      distance from left edte

      width

      px, pt ...

      width of the element

      width: 150px;

      height

      px, pt ...

      height of the element

      height: 80px;

      visibility

      z-index

      visibility visible

      default setting; element is visible

      hidden

      element is hidden

      visibility: hidden;

      1, 2, 3 ...

      establishes definite order of elements

      z-index: 2;

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Units of Measurement, Colors, and Special Characters

      46

      Units of Measurement, Colors, and Special Characters The Most Important Colors

      Country Codes for Character Sets

      English Name

      hexadecimal Value

      ISO-Standard

      Country Code

      UTF-8 (Unicode)

      universal character set, worldwide

      black

      #000000

      ISO-8859-1 (Latin-1)

      Western Europe, Latin America

      silver

      #C0C0C0

      ISO-8859-2 (Latin-2)

      Central and Eastern Europe

      gray

      #808080

      ISO-8859-3 (Latin-3)

      Southeastern Europe

      white

      #FFFFFF

      ISO-8859-4 (Latin-4)

      Scandinavia, Baltic Countries

      maroon

      #800000

      ISO-8859-5

      Cyrillic

      red

      #FF0000

      ISO-8859-6

      Arabic

      purple

      #800080

      ISO-8859-7

      Greek

      fuchsia

      #FF00FF

      ISO-8859-8

      Hebrew

      green

      #008000

      ISO-8859-9

      Turkish

      lime

      #00FF00

      ISO-8859-10

      Lapp, Norse, Eskimo languages

      olive

      #808000

      EUC-JP oder Shift_JIS Japanese

      yellow

      #FFFF00

      navy

      #000080

      blue

      #0000FF

      teal

      #008080

      aqua

      #00FFFF

      RGB Color Codes for CSS In CSS there is also the so-called RGB method of assigning colors. In the end, the colors on the screen consist of the elements red, green, and blue. So write according to the scheme

      Hover Links Here I’ll show you the four pseudo-classes for hyperlinks: • A:link is the normal hyperlink • A:hover is the hyperlink when the mouse passes over it, • A:active is the active link • A:visited is the visited hyperlink You’d like to highlight a link when the mouse passes over it? Then in the style sheet you’d write: A:hover {text-decoration: none; color: red;}

      rgb(RED, GREEN, BLUE).

      whereby the numbers 0 to 255 or the percentage values are allows. For the color green you could write

      Units of Measurement for CSS

      rgb(0, 255, 0)

      • • • •

      or rgb(0%, 100%, 0%).

      Codes for Special Characters Special Character

      Coding

      ä

      ä

      Ä

      Ä

      ö

      ö

      Ö

      Ö

      ü

      ü

      Ü

      Ü

      ß

      ß

      <

      <

      >

      >

      &

      &

      "

      "

      ‘ (apostrophe)

      '

      Here’s an overview of the units of measurement for CSS. Pixels, extension px Millimeters, extension mm Centimeters, extension cm Inches, extension in for inch, 1 inch equals 2.54 cm • typographic points, extension pt, corresponds to 1/72 inch • typographic Pica-points, extension pc, corresponds to 12 pt The most important units are pixels (for example, 14px), centimeters (0.5 cm), and points (12pt). For decimal values (0.5), you must be sure to use a dot (.) as the separator, not a comma.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Pull-down Menus

      47

      Navigating More Comfortably with Pull-down Menus Now we’ve spent a lot of time talking about indices, arrays, and zeroes; so it’s high time that we deepen our knowledge a bit. How would you like to find a more practical way to navigate? A pull-down menu? Let’s do it! Given, in the beginners’ booklet there was a similar example, if abbreviated. Here I’ll show you all the gory details in the long form so that you can understand what’s happening. The good news: even older browsers can parse the following script, something that you unfortunately can’t say about all scripts.

      Pull-down Menu with Go Button What do we want to accomplish? We’re offering the surfer multiple pages from which to choose. But simple hyperlinks are dead. The surfer can seek out the desired page using a list box. Then they click on Go and “off you go,” as the English would say. And the surfer lands almost immediately on the corresponding page:

      So that you’ll be able to do everything perfectly, first I’ll list the complete HTML document. Then, on the next page, we’ll discuss everything at length! Oh, and there’s something else: for the example you’ll need pagea.htm, pageb.htm, pagec.htm, and paged.htm. But by now you can prepare these files quickly. If you’re already ready to take a break: open the file pullgo.htm in the arrays folder! 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

      Go! <script language="JavaScript" type="text/javascript">

      Pull-Down Menu with Go Button



      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      48 23 24 25 26 27 28 29 30 31 32 33 34 35

      Pull-down Menus
      <select size="1" name="choice">

      Wow, at first glance this seems like a crime. But it’s really not. First let’s take a look at the HTML form, then at the JavaScript code.

      The source code for the HTML form You’re already familiar with the individual form fields? If not, please go back to the reference section and inform yourself. If you want to manipulate forms with JavaScript, you should name them. I’m emphasizing this because I get irritated by the countless scripts that address forms (graphics and other elements) using their index. This horrible number in square brackets [0] or [1] confuses people needlessly. Which is element 0, please, the form or the graphic? Let’s put a stop to this drama! In some cases it’s necessary to work with the index, but here it’s not. We’ll name our forms, form fields, and later on also the graphics using the form name="Name". Period. And we’ve done that too: have a look at the form in Line 23. It has been provided with the name list1. The form contains first a <select> field, Line 24. Right! We’ve named that too; the <select> field in our example is called choice. By the way, this naming is mandatory in HTML. With size="1" you assure yourself that only one value will be displayed, so that the <select> field will be a pull-down menu. Lines 25 to 30 contain the corresponding fields, that is, what’s necessary for the list box to drop down. Please imagine these 6 lines as as an array, as a field! Line 25 ensures that the index value 0, Line 26 is assigned value 1, etc., etc. The content of a <select> field is regarded as an array. (Unfortunately, in

      So that the script will function, you must call up the frameset file frameset.htm, not navi.htm. I’ll tell you more about the hierarchy in framed documents in just a moment.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Frames and JavaScript

      51

      Changing Several Frames at one Time Whoa! We’re still talking about frames? That’s right; I’d really like to show you more of these tricks. We’ll change two (or three?) frames at one time. But what’s the point?

      Changing Two Frames at Once Hmm. Take a look at this graphic. It comes from the tips and tricks section of my homepage:

      Creating the exemplary document First let’s think about making an exemplary file for our frame project. You’ll need exactly seven documents! Why? Because three documents are responsible for the navigation; I’ve called these navia.htm, navib.htm, and navic.htm. Here you’ll highlight a different link for each document. But we’ll create these documents in the second part of the exercise. The documents to be displayed in the main frame are called maina.htm, mainb.htm, and mainc.htm in our example. Here’s where the actual contents are displayed. If you’d like, you can go ahead and build these pages now since this isn’t hard to do. These are completely normal, 100% script-free HTML files. But back to the naming. Did you notice anything? Right, we’ve chosen the names with some care! Both navia.htm and maina.htm end with a, navib.htm and mainb.htm both end with b, etc. This is the trick to the whole thing!

      The document is divided into three frames. If the surfer clicks on a rubric in the navigation frame on the left, the corresponding contents are loaded into the main frame (on the right). In addition, the navigation frame and the title frame (above) are changed too! Cool! This is how, for example, a link that you’ve just clicked can appear highlighted. And in the title frame you can incorporate another title if you wish. But frames are by reputation a can of worms. So that you’ll see what’s what, let’s take an easy example! And we’ll confine ourselves – sensible as we are – to a two-part window:

      So now we’re just missing the seventh document, the frameset. And that should look like this. In the example, I’ve called it frameset.htm. Copy it and place it in the same folder as the three main documents. On my computer, all the project files are in the folder frames. 1 2 3 4 5 6 7 8 9

      Frameset

      Do you understand how this frameset works? These are just the instructions for dividing the window. It should be in two columns. We’ll be generous and make the left column a roomy 110 pixels. The right column remains variable (*). First the file navia.htm is loaded into the left frame. In the right frame (main frame), you’ll see maina.htm at the start. And as we said before, the whole name-id stuff and the slashes with “compatible empty spaces” serve only to conform to XHTML syntax. It’s easy to get used to.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Frames and JavaScript

      52

      The Hierarchy in Frames

      An overview of the source code

      Now let’s have a look at the navigation documents. But before we do that, I’m going to subject you to more theory. If you’d like, you can read through it and forget it as soon as you’re done.

      First let’s make sure that you understand that we’re in the navigation frame, that is, on the left-hand side.

      In JavaScript, frames are arranged hierarchically. The actual frameset is addressed using the keyword parent. The actual frameset (here frameset.htm) is regarded as the “parent window”. The individual frames in this game are the children. The children are named in the frameset, here with main and navi. You’d like to have one framed document refer to another document in another frame using JavaScript? The frame to which you’d like to refer is called main? The document that you’d like to display there is called maina.htm? Then you need to begin with the “parents.” You’ll use the “beloved dot notation” to access the actual document:

      In Line 7, notice the function that I’ve called frame(page). Again, this is a function that has a parameter passed to it.

      parent.main.location.href ="maina.htm".

      The first navigation file

      Back to the script. Line 9 changes the contents of the current frame. Here, the file name is put together using the string navi and the value returned by the variable page, so in our example (Click on Line 17) this would be navib.htm.

      Here’s the complete source code for the page navia.htm. We’ll explain what’s hiding behind it in just a moment!

      Lines 16 to 18 are responsible for the links. Here the function frame(page) is called and fed the appropriate parameter (a.htm, b.htm, etc.).

      1 2 3 4

      And now you can see why we were so careful about giving good names. It’s simple, but a stroke of genius, don’t you think?

      Great. And now let’s have a look at the source code for our navigation document.

      5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

      Navi A <script language="JavaScript" type="text/javascript">

       

      Page A

      Page B

      Page C



      When you’re copying this code, make sure that you don’t break up the individual lines.

      First in Line 6 we declare – because we’re good citizens – a variable called page.

      Line 8 concerns itself with changing the main document, which can be found in the right-hand frame. Using dot notation, we refer, beginning with the “parent,” directly to this frame using the frame name. But what happens here behind the equals sign? Here, using the string main and the contents of our variables, the file names are put together. If you “click on Line 17,” the variable page is fed b.htm and the resulting file name is mainb.htm.

      Now for the other two navigation documents: build the same script in here. Only the hyperlinks in the body need to be adjusted. For the document navib.htm, Lines 16 to 18 would look like this: 16 17 18

      Page A

      Page B

      Page C



      In navic.htm, by contrast, they’d look like this: 16 17 18

      Page A

      Page B

      Page C



      Given this example, surely you can cobble together more complex frame projects.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Frames and JavaScript

      53

      Further Tips and Tricks for Frames On this page I’ll tell you about two easy but very useful scripts. Try building them into your framed documents.

      Forcing a page into a frameset Working with frames is just one of those things: often search engines don’t index the frameset, but instead individual, framed files. Since the link leads directly from the search engine to the corresponding document, it will be displayed completely without a frame. It’s a scandal! The whole effect is lost! So here’s how you can make your page hop quickly back into the frameset every time. This simple script will help you: 1 2 3 4 5

      <script language="JavaScript" type="text/javascript">
      6

      //-->

      7



      The code is easy to explain: Line 3 checks, with the help of an if statement, whether the “parent document” is the actual document. That is, whether the document to be displayed is unframed because it doesn’t have a parent frame. And exactly this cannot happen! If this is the case, however (given a direct link from a search engine, for example), the parent document is assigned the URL of the frameset, here frameset.htm. Have a look in the frames folder, in the subfolder special. But for the file mainc.htm, I’ve “handled” all documents subsequently with this script. You can call up these documents individually and they’ll find their way into the frameset anyhow. But there’s one catch to this script: the frameset is always called up in the “starting position.” In the example, therefore, navia.htm and maina.htm appear on the screen even if mainb.htm is called up. You can only solve this problem by creating an individual frameset for each document and calling this up with the function.

      Freeing pages from a frameset The other extreme can also occur: I’ve heard that there are actually people out there who put “foreign” pages into their own framesets and “sell” them as their own. This isn’t good style and, in addition, it’s downright dishonest. To guard against this, you can use a script that frees pages from a frameset! <script language="JavaScript" type="text/javascript">

      Try it. The file mainc.htm in the special folder has been given this “special treatment.” When the frameset calls it, it takes over the whole browser window for itself. And rightly so!

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      54

      Changing Text and Tickers

      More Dynamic, Please: Changing Text and Tickers Great! So now I’ve enlightened you about names and forms and I’ve beat you about the ears with arrays until your head hurts. You’ve probably even got the setTimeout() method and counter variables coming our your ears. And just as annoying as these elements are the everlasting banners and tickers. They wave and tick on enough pages that they probably make you sick by now. But despite this, we should take a look at how these tickers work since we can learn a lot from them. In addition, the fun factor is so high that this topic is worth covering.

      Displaying Changing Text in Form Fields Let’s start quite sensibly with a form field, which, at an interval of some seconds, will present a different text each time. For this purpose, let’s use a text entry field. For this kind of field can be used for display and it’s also wonderfully well-suited for our dynamic experiments!

      Reminder: the syntax for a text entry field looks like this:

      And now here’s the complete HTML document in brief. Compare it with changingtext.htm in the arrays folder. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

      Changing Text <script language="JavaScript" type="text/javascript">

      Words change thyselves!



      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Changing Text and Tickers

      55

      The source code in brief First cast an eye over the form in Lines 28 to 30. Don’t forget to name the form and text field! With size=”50” you take care of setting the proper width. Otherwise the text field will be too narrow. And now to the script: in Line 6 I declare two variables. The counter variable i is set to 0 in Line 7. We store our message in Lines 8 to 12. Here we’re talking about – surely you suspected it already – an array. In this case you should note one very exciting thing – these are global variables! Global variables are available in all parts of a program. They are initialized outside of a function. By contrast, local variables are only available in a particular part of a program, for example, within a function. Our function begins in Line 13; in the example it’s called changetext(). And in Line 14, this function writes the first text into the form field. Here the form field itself is addressed with document.form1.textfield.value, that is, using dot notation. This field is first assigned the value message[i]. And since the first value of i is 0, the first text in the array (index 0!) is displayed. Line 15 contains an if statement. If i is smaller than the length of array-1 (message.length-1), the counter variable is incremented by one. But what is message.length? It’s the length of the array, in the example, 4 (the array contains 4 elements)! But because the starting value is 0, we must subtract 1 from 4. Thus only when i equals 3 does the counting stop. Then (else) in Lines 18 to 20, our counter variable is assigned the value 0 once again. In Line 21, our spiffy setTimeOut() method specifies that the function is called every 5 seconds (5000 milliseconds) and our counter variable can keep counting along its merry way. And how is the script called up? Using onLoad in the tag; see also Line 26.

      Changing Text on the Status Line And nobody is stopping you from displaying your “changelings” in the status line. To do this, you’ll just need to replace document.form1.textfeld.value in Line 14 with window.status. After this “cosmetic surgery,” the complete Line 14 should look like this: window.status=message[i];

      You can delete the form from your document. Have a look at the file changingstatus.htm in the arrays folder.

      Programming a Ticker: The String Object in Brief I’m afraid that I owe you an explanation of the typewriter ticker in my beginners’ booklet. Unfortunately, that project was programmed with such brilliant abbreviation that the code is hard to take apart. Therefore here we’ll build the long form! This is also a good opportunity to introduce you to a new object and a few much-beloved properties and methods.

      Properties and methods of the string object Precisely, the string object. I’m sure you’re already aware that string stands for a string of characters. I’ve already shown you how you can extract the length from a string. (Namely, using the property length.) But the other methods are worth a look too. Most of them we’ll need badly later on!

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Changing Text and Tickers

      56 Property/Method

      Explanation

      Example

      length

      this is the only property for which you don’t need parentheses. It returns the length of a string as a numeric value.

      zip.length

      charAt(x)

      returns the character at position x in a text string. Counting begins with 0.

      charAt("super")

      substring(Position1,Position2)

      returns the characters between two positions in a string, counting begins with 0, position2 may never be reached.

      important="holiday";

      this method transforms a string into upper-case characters.

      e5=e5.toUpperCase()

      toLowerCase()

      this method transforms a string into lower-case characters.

      t1=t1.toLowerCase()

      split()

      this method transforms a string into an array using a particular character as a separator. This depends on the string and the separator cannot be a comma.

      document.cookie.split("; ")

      as=important.substring(0,5); alert(as);

      toUpperCase()

      Don’t be alarmed; now we’ll try this using an example. The first time around we won’t use the split() method; we’ll get to that when we talk about cookies! 1 2 3 4 5 6 7 8 9

      var word; word=prompt("Please enter a noun!",""); alert("Your word is " + word.length + " characters long."); alert("The third character is a: " + word.charAt(2) + "!"); alert("The word ends with: " + word.charAt(word.length-1) + "!"); alert("The first two characters are: " + word.substring(0,2) + "!"); alert("Your noun will look like this in 20 years: " + word.toLowerCase() + "!"); alert("But that is better than: " + word.toUpperCase() + "!"); alert("Thank you for your cooperation!");

      Have you copied this code and saved it in an HTML document? Or have you secretly opened the file strings.htm in the strings folder? Then let’s try an experiment! Type the word lazybones in the prompt() box. This string is stored in the variable word and taken apart character by character. Line 3 will inform you that this word is 9 characters long. Line 4 will show you the third character (z). Since the counting begins with 0, you need to enter a 2. Line 5 will show you the last letter. Because counting begins with 0, you need to subtract 1 from word.length. Line 6 shows you the first two characters. Lines 7 and 8 transform the string into lower-case, then into uppercase letters. Line 9 doesn’t have anything to do with the string object. I just included this stupid saying that comes from science fiction novels, where many people die because the computer goes crazy. Upon each death, the electronic brain thanks the person for their cooperation. I hereby thank you for your attention and I’ll show you a practical example: the typewriter ticker with the substring() method.

      Typewriter Ticker with the substring() Method The principle is simple. The substring() method returns the string between two values. We’ll always leave the first value at 0 and we’ll just increment the second value in steps of 1. For this, I’ve used the variable pos. In addition, we can go ahead and combine the typewriter script with the “changing text” above. Here’s the complete HTML page at a glance: 1 2 3 4 5 6 7 8 9 10 11 12 13

      Changing Text <script language="JavaScript" type="text/javascript">
      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Changing Text and Tickers 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

      57

      if (pos<=message[i].length) { document.form1.textfield.value=message[i].substring(0,pos) + "_" ; pos++; setTimeout("typewriter()",100); } else { pos=0; if (i<message.length-1) { i++; } else { i=0; } setTimeout("typewriter()",1000); } } //-->

      Typewriter



      The source code in brief Surely the first lines are already more or less familiar to you. The new element is the variable pos, which is assigned an initial value of 0. All variables start as global variables, that is, outside the function. The rest up to Line 12 should be clear; it describes our wonderful array. In Line 13, we introduce a function, which I’ve called typewriter() this time around. In Line 14, we encounter the first of many if statements. It checks whether the contents of the variable pos (at the beginning, 0) are smaller than or equal to the corresponding text string in the array. (It doesn’t check the number of elements in the array, which is 4 in total, but the length of the text string.) If the length of the text string has not yet been reached, then Line 15 takes over. The first time, none of the text in the array is written into the form field since substring(0,0) is nothing. Be aware, however, that with the help of the string operator + I’ve displayed an underscore. This heightens the “show effect.” document.form1.textfield.value=message[i].s ubstring(0,pos) + "_" ;

      Line 16 increments the variable pos by 1, Line 17 makes sure that the function is called again. Ticker, ticker, ticker…in a few seconds, the first “text string” is constructed and at some point the variable is exactly as large as the length of the text string. Look at Lines 19 and 20: now else comes into play. And else places the value of pos back at 0. And rightly so. Now the program checks to see what’s up with i; it does this in Line 21. And using i, you read out the length of the array, here 4. If i is smaller than 4-1 (3), then everything is in order. Then the other text strings in the array should get their chance. Therefore: the variable i is incremented. The function then continues in Line 27. Here again – after a 1-second pause – the program refers to Line 13. The game begins again from the start and the next text string is processed. But what happens if the counter variable i takes on a value of 3, that is, when all positions have been processed? Then the second else comes into play, this in Lines 24-26. Then i is set back to 0 and the array can be run through from the beginning. You see, it’s difficult to understand this function.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript

      58

      Evaluating Forms with JavaScript Give me feedback! Forms are everywhere. But only with the help of JavaScript do forms really become important. Did you know that the handling of errors in forms was a primary motivation for the development of JavaScript? Before we get too far into this important theme, I’d like to reveal to you a few pecularities of evaluating forms. In principle, you should already know forms inside and out. In the beginners’ booklet, I used an example to show you how to evaluate forms. You’ll get – at least if you read the first or second edition – an e-mail with an attached file. But it’s more comfortable if you include the attribute enctype="text/plain" in the
      tag. Then you’ll receive the data directly in the body of the e-mail message. Umlauts are no longer mangled. Have a look at the reference section to see an exemplary form of this type. It doesn’t make a bit of difference to the form itself how it’s evaluated. Despite this, however, large firms prefer to have the contents of forms sent to them using CGI rather than in an e-mail message. But what’s really behind this?

      What’s Behind CGI Let’s begin with what it’s not: a programming language. CGI is only the “connecting link” between user input and programs running on the Web server that react interactively to user input. There are many examples of this: just think about a counter, a guest book, shopping cart programming for an Internet shop, or form evaluation. Here your user input is conveyed immediately to the server, and in particular, to the respective CGI program. This program reacts to the input and, depending on demand, returns the desired data in real time (that is, right away). As a rule, this process is connected to access to a database, which is found on the server. CGI is, therefore, not a programming language itself, but just a link. In which programming language a CGI script must be written depends on what operating system is installed on the Web server. If, for example, the server is running NT, then CGI scripts can be written in Visual Basic, C+ or C++. Apple Script is used on Macintosh computers.

      The king of the CGI programming languages, however, is Perl. Perl runs on the popular UNIX operating system. Most Web servers are based solely on UNIX (or Linux). Whoever wishes to make their Web page interactive by using CGI scripts must know for sure which operating system the server is running (as a rule UNIX or Linux) and whether they’re allowed to publish their own scripts on the server! Precisely the last condition is not a given. Many Internet service providers including T-Online and AOL don’t allow you to run your own CGIs! And even “home page discounters” like Puretec or Strato in Germany will only let you run CGIs for a rather steep price.

      FormMail as an Alternative to mailto But back to form evaluation. The form evaluation trick I showed you with action=mailto is a nice thing since you can use it independently. The drawbacks, however, are obvious: the user must have a correctlyconfigured, functional e-mail program. So you’d like to receive the contents of the form via e-mail anyway, and preferably without the disadvantages of the „mailto method“? Then I know just what will help you: the free CGI program FormMail, which is a “form to e-mail” program. The form contents are read out of your HTML form and sent as an e-mail message to the specified address. Therefore, in contrast to the „mailto method,“ the surfer doesn’t have to have an e-mail program installed. The input is processed on the server. You’ll find the free program FormMail at: www.worldwidemart.com/scripts/formmail.shtml. But what if you aren’t allowed to run CGI programs on the server? Then just surf to the page www.homepageforum.de, in particular to www.homepageforum.de/add-ons/formmailer.shtml! Here you can use FormMail for free. Exact (Germanlanguage) instructions for constructing forms are here: www.homepageforum.de/add-ons/formmaileranleitung.shtml.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript

      59

      The Example: An Order Form in HTML Let’s try this example together. I’ve thought up an order form for a product. Surfers are supposed to select the desired quantity, delivery method, and color. In addition, they’re supposed to enter their first and last names, customer number, and e-mail address. I’ve skipped having them enter their street address; instead, I’ve used the customer number. If you’d like to have a picture of the form in your head, just look at the illustration. Just so you know: forms are also often arranged using invisible tables. If you’d like, you can make your project more complicated. But two lines were enough for me. You’ll find the project under the name form1.htm in the forms folder. Have a look at the HTML source code for the form: Order

      Order a product!

      The product costs $35 US and the shipping costs are $6 US.
      I would like to order of this product.
      Express Delivery ($10 US extra)
      I would like it in the color Black Silver Gold

      Title: <select name="title" id="title" size="1">
      First name:
      Last name:
      Customer number:
      E-Mail address:



      Given your previous knowledge of HTML forms, you should be able to deduce quickly how this works. I’ve tried to include the most important form fields. If something is unclear to you, have a look at the reference section. The form contains several cosmetic flaws, which we’ll correct together.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript

      60

      Preventing Accidental Reset and Submit You’re no doubt familiar with the Reset button, which serves to clear form contents and reset the form. But this button presents a greater danger on long forms. Have you ever filled out a yard-long form and then accidentally clicked Reset? Poof! All of your data is gone and you have to enter it in again. Just as dumb is if the user doesn’t fill out the form and then, just for fun, clicks the Submit button. Your CGI database on the server or your e-mailbox will be filled with senseless, empty messages. So let’s put an end to this nonsense! Let’s build a routine with JavaScript that will check the reset and submit events. After clicking Reset or Submit, a reset or submit event is sent to the form. You can capture this with the onReset or onSubmit event handler and send the results to a function. If this function returns the value true, then fate will take its course. But if it returns a “false message,” then the Reset or Submit will be prevented. OK, off to battle! But before we begin, I must introduce you to a much-loved new method without which we can’t win the war.

      The confirm() Box I’m talking about the confirm() method. It creates a dialog box just as alert() does. And just as with alert(), you can output text strings and variables in this box. Here’s what our cool confirm() box looks like in practice:

      Did you notice anything? Right, in contrast to alert(), confirm() has two buttons, namely OK and Cancel. In addition, confirm() has one further interesting pecularity, which we can exploit shamelessly for our purposes. Depending on what is clicked, confirm() returns the Boolean value true or false. A click on OK will return the value true, while a click on Cancel will return the value false.

      The Script for Capturing the Events Now then, let’s build the script for our “safety net for forms” together. We’ll put it in a function that will be called by onReset or onSubmit. I’ll give this function the name safe().Voilà, here it is; place the function in the customary position in the document. function safe(question) { var answer; answer=confirm("Are you sure that you want to " + question + " this form?"); return answer; }

      It’s a function that expects parameters, as you can plainly see. The variable answer captures the value true or false and returns it with return answer. The variable question (the parameter for the function) is “fed in” when the function is called. And where do we call this nifty function? In the
      tag. Just add the following attributes to the tag: onReset="return safe('clear')" onSubmit="return safe('send now')"

      You’ll find the new and improved form in the file form2.htm.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript

      61

      Checking Form Field Entries Now we’ve taken care of the accidental reset and submit, but what happens if the customer sends data off in good faith but has forgotten to fill out an important field on the form? Without a customer number, you can’t access the address! And all the other fields should be filled out too. Surely the customer would be happy to know exactly what information is required to place an order. We’ll take care of all of this, one thing at a time. First we’ll build some cool buttons into the document. To do this, you’ll need to add a couple of really short code lines that will take care of the Reset and Submit buttons:



      I’m sure that hardly a customer could resist the charm of this offer. If the customer clicks this button, it calls the function formtest(). And now we need to create this together.

      Checking Fields to see if Anything was Entered We’ll build the function step by step until we’ve constructed a powerful routine. First let’s begin sensibly by checking all the fields for entries. In the illustration, we’ve forgotten the customer number. After clicking our new button, formtest() springs into action. The preliminary routine for this looks as follows: 1 2 3 4 5 6 7 8 9 10 11 12

      function formtest() { var firstname, name, custnr, email; firstname=document.input.firstname.value; name=document.input.name.value; custnr=document.input.custnr.value; email=document.input.email.value; if (name=="" || firstname=="" || custnr=="" || email=="") { alert("Please fill out all fields!") return false; } alert("You passed the test."); }

      The program checks the contents of the form fields with an if statement. At first, we just need the fields firstname, name, custnr, and email. Lines 3 to 6 demonstrate beautifully how you can read values out of simple text form fields. You begin with document, then branch out to form names (input), then on to the name of the form field (in Line 3, for example, firstname) and transmit the value. If one of the fields is empty, an alert() box pops up and program execution ends. Otherwise, the script will display a preliminary placeholder box “You passed the test.” It stands for that which we will be programming (the calculation and display of the data in an extra window). Just as an aside: the parallel lines (||) are the (either)or operator that allows us to kill several birds with one stone. This is a logical or. The second operand is only evaluated if the first one is false. The empty quotation marks don’t mean anything more than “empty.” If the first field is filled out, then the second is checked. If all fields are empty, then the if statement will always return false. The script continues after the if statement and displays our “placeholder box.” You’ll find the script up to this point in the file form3.htm.

      Password check Let’s assume that you’ve set aside two fields for entering passwords. The second field serves as confirmation. How can you tell whether password field 1 and password field 2 contain the same data? Read the values out of the form fields and compare them! Of course with this method you can only check if the surfer made a typo. Whether the password is actually correct is something you’ll find out only later on. if (pw1!=pw2) { alert("Please check the password!"); }

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript

      62

      Zip code test And what about the zip code? This field must be 5 characters long. So let the length property help you. The check might go like this: if (zpcd.length<5) { alert("That is not a valid zip code!") }

      So your fantasies need know no bounds! Just formulate the condition that you need. React to it. Here are some more possiblities that might be useful to you when building your own forms:

      Test when leaving: onBlur You can also trigger the desired test function directly from the form field. For this, use the onBlur event handler. In the following example, the function mailcheck() is called when the user leaves the e-mail field.

      Forcing the User into a Form Field: focus() Methods You can also place the focus on a particular field. For this, use the focus() method. It places the cursor back into the desired form field. In the example, we’ve used the e-mail field: document.input.email.focus()

      Marking Form Fields:select() Methods Just as useful in some cases is the ability to mark a form field. You can do this as follows: document.input.email.select()

      But back to our function. Next I’ll show you how to build in an e-mail check!

      Checking the Validity of E-Mail Addresses Let’s assume that you attach special importance to the email address. Up to this point, we’ve only checked whether the user entered something in the e-mail field: but the surfer could type in anything, even something that has nothing to do with an e-mail address. Go ahead and test whether the entry fulfills certain prerequisites. Each e-mail address contains an at sign (@) and a dot (.). In addition, it should contain at least 7 characters. Use the abovementioned charAt() method and a counter loop to test whether the string input contains the appropriate characters. Here’s the complete and substantially expanded function with the “deluxe” e-mail check. The explanation follows. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

      function formtest() { var firstname, name, custnr, email, at, dot, i; firstname=document.input.firstname.value; name=document.input.name.value; custnr=document.input.custnr.value; email=document.input.email.value; if (name=="" || firstname=="" || custnr=="" || email=="") { alert("Please fill out all fields!") return false; } at=0; dot=0; for (i=0; i<email.length; i++) { if (email.charAt(i)=="@") { at=1; } if (email.charAt(i)==".") { dot=1; } } if (at!=1 || dot!=1 || email.length<7) { alert("That is not a valid e-mail address!");

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Evaluating Forms with JavaScript 23 24 25 26 27 28

      63

      document.input.email.focus(); document.input.email.select(); return false; } alert("You passed the test."); }

      In the example you’re using two variables as “flags.” These are two “flags” that you wave in case of success and evaluate. In our example, if the flags are set to 1, then both @ and a dot are present. The new variables in the example are called at (which checks to see if “@” is present) and dot (which checks to see if “.” is present). In Lines 11 and 12, both of these variables are initialized with a value of 0. A counter loop runs through the string input by the user from start to finish. If the appropriate character is present (here @), the value of the variable is set to 1. This happens in Line 15. Another counter loop tests the same thing for the dot. In case of success, the value of dot is changed from 0 to 1. Please note that you must use two curly brackets at the end (Lines 19 and 20). One of these ends the if statement, the other ends the counter loop. In Line 21, another if statement becomes active, which tests our “flags” and at the same time checks to see whether the minimum length of 7 characters has been reached. If one of the conditions isn’t true, then the obligatory alert() box (Line 22) will appear. With Line 23 you place the cursor back in the e-mail field. Line 24 ensures that this field will be marked. You’ll find the current state of the art in the file form4.htm.

      Calculating the Result In the end you calculate the result and display it for the surfer, complete with their name in an alert() box. In the foregoing version of the formtest() function, you just need to add a variable in Line 2. The line should now look like this: var firstname, name, custnr, email, at, dot, i, result;

      In addition, you’ll need to delete the placeholder alert() box in Line 27 and add this code: result=document.input.quantity.value*75 result=result+12 if (document.input.express.checked) { result=result+20 } alert("Hello, " + firstname + " " + name + ", you will pay " + result + " $!");

      The first line reads out the value of the quantity field and multiplies it by 75. Then the result is stored in the variable result. In addition, 12 is added to this value for shipping costs. If the customer has selected express delivery, then another 20 is added to the result. And now an alert() box displays the customer’s last name, first name, and total. You’re wondering what the character \n is doing in the alert() box? This is how you put a line break in a dialog box. But you can also leave this character out. You’ll find the result of all of this in the file form5.htm. Using this model, you can program more complex form evaluations. Display all the data for the surfer again. If you’d like, you can display the data in a cooler window created “on the fly” rather than in an alert() box.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      64

      Banners and Dynamic Buttons

      Mouseover Effects and Banners At last! It’s time! Naturally you’ll also find the renowned onMouseover scripts for dynamic buttons in this booklet. I already explained all the prerequisites in the beginners’ booklet. You’ll need a pair of graphics of exactly the same size. One is the normal, the other the “highlight” graphic. The graphics could, for example, be called know1.gif, know2.gif, service1.gif, and service2.gif. The second graphic is in each case the one that should be displayed at “onMouseover.”

      The principle is simple: if you pass the mouse pointer over the button with the graphic on it, the graphic, thanks to the onMouseover event handler, should be replaced with the second graphic. When leaving the link (onMouseout), the second graphic should be replaced with the first one again. You’ll find the example in the images folder under the name dynalink.htm: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

      26 27 28

      29 30 31

      Hover Graphics <script language="JavaScript" type="text/javascript">

      OnMouseover-Buttons



      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Banners and Dynamic Buttons

      65

      The source code in brief Let’s have a look at the script. What’s with the if statement in Line 6? With document.images I’m finding out whether or not the browser can even understand the images object. If the surfer is surfing with Netscape 2 or Internet Explorer 3, the answer is no. This is purely a safety measure. Without this question, an error message would appear. Whoever has such an old browser will see Lines 16, 17, and 18. In Lines 7 to 14, all the graphics are pre-loaded as so-called object variables. This is important so that the highlight graphic is available immediately upon onMouseover and it doesn’t have to take the time to load after the fact. So, and now let’s have a look at the BODY of the HTML document. The most important element in the whole story is the naming of the graphics. I’ve done this in Lines 25 and 28. The first graphic is called know, the second service. In addition, you should provide the height and width for each graphic and suppress the frame. If you’re uncertain about the syntax for adding graphics, take a look at the reference section. And what, exactly, happens in Line 25? Upon OnMouseover, the graphic with the name know is assigned the contents of the variable know2 via document.know.src. It’s also important that upon onMouseout, the first graphic be put back into its original position. Try customizing the example and adding additional graphics.

      OnMouseover Effects with Hover Links Since we’re already talking about onMouseover, we should take a closer look at these hover links. You’re already familiar with text links that change color when you pass over them, or ones that don’t appear underlined anymore, or ones that get larger, etc. No script is necessary for these, you just use CSS (style sheets)! You’ll need the so-called pseudo-classes. With these you can address the four link conditions using CSS. A:link is a normal hyperlink. A:hover is the hyperlink when it’s passed over with the mouse, A:active is the active link, and A:visited is the visited hyperlink. You’d like to highlight a link when it’s passed over with the mouse? The hover link will suffice for this. Then you’d write in the style sheet: A:hover {text-decoration: none; color: red;}

      But you can address all link conditions in this manner, for example, you can turn off the borders around a hyperlink. text-decoration: none will take care of this. Remember that Netscape 4.x can’t interpret A:hover. Furthermore, you should know that the settings for A:visited override everything else. The surfer has visited your page already? Then, for example, the color you set for A:hover (or the underlining to turn off) won’t work anymore since another color is specified in A:visited and/or the underlining is turned on again. Visited is visited! What can you do about this? Just omit these properties of A:visited. For the “visited link” you can still define another color. Do this in the tag using the familiar attribute vlink (see the reference section). Here’s the source code for the exemplary document hoverlink.htm, which is in the images folder: Hover Links <style type="text/css">

      Hover Links

      KnowWare Deutschland KnowWare international

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Banners and Dynamic Buttons

      66

      Script for a Banner Advertising banners are playing an ever-larger role on the Web. Usually, different graphics are blended together. If you click on the banner, then a hyperlink will whoosh you off to the advertiser’s page. As an alternative to a JavaScript banner, I recommend so-called GIF animations. The Paint Shop Pro program that I recommended in the beginners’ booklet comes with a complete GIF animator. The no-cost StarOffice also contains a program for creating animations. But back to our project. We’ll solve the problem with JavaScript. First you need to create the desired number of graphics in the appropriate size. All the graphics must be the same size, for example, they could measure 400 x 100 pixels. These are five JPG graphics, of which you can see three here:

      The script itself is very easy to understand: first all the graphics are saved in an array. With the help of a counter (nr) and the setTimeout() method, you change the graphics every 3 seconds. By using an array you can add or take away as many banner pictures as you want. You’ll find the example in the file banner.htm in the image folder. Banner <script language="JavaScript" type="text/javascript">

      Banner



      No doubt, you can easily develop this script further. Use it to make a slide show in which the pictures change only when a button is pressed. Build in buttons that will take you a picture backward or forwards, or let you jump to the beginning or end of the show. With JavaScript, doing all these things is no problem!

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Cookies

      67

      Programming and Reading Out Cookies Many wild rumors about cookies are flying around within the surfer community. They can retrieve data from your hard disk. Cookies are a big security risk and an entry point for viruses. Nonsense! Do you still think there are monsters under your bed? No? Then you don’t need to be afraid of cookies either. Cookies are nothing more than text files that a Web site uses to store information on your computer. I repeat: a Web site stores information on your computer so that it will know that you’ve been there. A Web shop takes note of which products you’ve put in your shopping cart. On demand, all the information can be read out again. Internet Explorer generally stores cookies in C:\Windows\Cookies; the Netscape browser chooses the path C:\Program Files\Netscape\Users\Username. In case you can’t find them, try searching for the keyword cookies with the Windows Find function. If you’re using a computer that has multiple users, you’ll probably have to search for the cookies. Watch out for dates! You can go ahead and have a look at the cookies and delete them if you wish. OK, so the data is stored on your hard disk. And it can only be read out by the page that placed it there. Or, to be more precise, by an HTML document from the same folder or HTML pages from subfolders. But normally not by another domain! Cookies are usually a private issue between the Web site, your browser, and you. Understand?

      “Recognizing” a Surfer with the Help of Cookies Cookies are looming everywhere. Let’s head for the cookie jar! But now you’re the one who has to distribute the cookies. You place a cookie on the surfer’s page. Upon their next visit, “you” read it out again and the surfer will be greeted “personally.” Here are a few snapshots of the first example. I dare you to find the difference!

      Behind this lies the following source code, which you’ll also find in the cookies folder in the file cookie.htm: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

      Cookie <script language="JavaScript" type="text/javascript">

      Placing and Reading Out Cookies



      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Cookies

      68

      The cookie Property, setMonth() and Cookie-Syntax Now it’s time to learn something else new. When you place a cookie, you use the cookie property of the document object: document.cookie="cookiename=cookievalue; expires=DateinGMTFormat"

      So that the cookie has an “expiration date,” you’ll need the keyword expires and next to that you must write the date in Greenwich Mean Time (GMT) format. The GMT format is mandatory. In order to transform a date into the GMT format, you’ll need to use the method toGMTString(). With the command date.toGMTString(), you’ll transform the contents of the variable date into the corresponding GMT format. In the course of this, the date will, by necessity, be transformed into a text string. Furthermore you’ll need to use the method setMonth() in the script. This determines the month, whereby counting begins with 0=January. You’d like to specify May? Then you’d write date.setMonth(4).

      The script in brief With this knowledge, it should be easier for you to understand the script. After declaring the variable date, the script checks in Line 7 whether a cookie is present. If it is, then this means that the surfer has been here before. Then they’ll be greeted with the nice text in Line 8. Or, if it’s the surfer’s first visit, Lines 10 to 12 will be activated. The only difference is that the little word again is missing. Lines 13 to 15 are especially important: in Line 13, date is initialized as an object variable. In Line 14, the month value is set. It’s calculated by taking the current value + 3. The cookie will then have a life expectancy of 3 months. After that, it will delete itself from the surfer’s hard disk. In Line 15, by contrast, a cookie with the name alreadyhere is assigned the value yes. In addition, the whole thing is linked to the date. The contents of the variable date (now the current date plus 3 months) must be available in GMT format.

      Reading Out One Cookie from among Many But this script has a catch. We’ve placed one cookie. For a “has the surfer been here already question,” this is OK. After all, our test was simply to read out and check whether a cookie had been placed. But what if you’d like to save concrete values and read these out again? Then you have to proceed differently!

      For our next project we’ll build two files since this will help us keep perspective. The first document should place the cookies. The second, by contrast, will read out the individual cookies and react to them. Both documents are in the same folder (if you were to place the document you’re reading out of one folder level higher, it wouldn’t be able to find the cookies!). The project works with “Version 4 browsers” and higher. First the source code of the “placing document,” which I’ve called placecookie.htm. Pay attention to the naming of the cookies, yourname and hobby. The actual values are read out of the fields of a form using onBlur(). Surely you’ll have no problems reading and understanding this script. Baking Cookies <script language="JavaScript" type="text/javascript">
      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Cookies

      69

      date.setMonth(date.getMonth()+3); yourname=document.cookieform.yourname.value; hobby=document.cookieform.hobby.value; document.cookie="surfername=" + yourname + ";expires=" + date.toGMTString(); document.cookie="hobby=" + hobby + ";expires=" + date.toGMTString(); } //-->

      Please fill out the form:

      Your Name:
      Your Hobby:

      The “reading” Document But what’s happening in readcookies.htm, of which I’m only showing you the JavaScript portion here? 1 2 3 4 5 6 7 8 8 10 11 12 13 14 15 16 17

      var cookies, i, cookiesname, cookiesvalue; if ( document.cookie=="" ) { document.write("How nice that you are here!"); } else { cookies=document.cookie.split("; "); for(i=0;i
      I’ll only say that split() reminds me dimly that I’ve already explained this string method to you. It transforms a character string into an array. Thereby a particular character is designated as the separator. Important to know: as a rule, cookies land in a single text file, whereby one cookie is separated from another internally by just a semicolon (;) and an empty space. And cookiesname and cookiesvalue have an = as their separator. Does this ring a bell now? Line 6 specifies precisely this (semicolon with an empty space) as a separator, and so we can create a marvelous array of all the cookies. Now you can address each individual cookie using its index value. A counter loop in Line 7 counts through all the cookies and increments the counter variable i. Next, cookiesname (the name of the cookies, that is whatever is in front of the =) and cookiesvalue (the string after the =) are transmitted using the split() method and stored in the appropriate variables. Note: each individual cookie is also an array that consists of two parts. In Lines 10 to 13, the names of the cookies are compared using if statements. If the name we’re looking for is there, the script reacts and displays the corresponding value (the variable cookiesvalue). This is as easy as it is brilliant. And it even works with the Netscape browser (Version 4 and higher). In this way you can extract more information and react to it. Which pages does the surfer like to visit? On the next visit, lead them right there. How often were they here? Remind them each time.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      DHTML

      70

      DHTML: Addressing CSS Containers and Levels What in the world is DHTML? A fashionable word! The abbreviation stands for Dynamic HTML. But we’ve already seen examples of dynamic applications: consider the ticker, moving text, hover links, mouseOver graphics, and the time. Correct. And if you understand DHTML in this broad sense, we’ve been “baking” DHTML the whole time. In a narrower sense, DHTML refers to the capability to address and manipulate elements with a style sheet. In this whole story, there are several potholes: the Netscape browser and Internet Explorer use different object models. That which you access in the Netscape browser via layers you must address in Internet Explorer via the corresponding style sheet property. In addition, Netscape 4.x still has trouble with CSS. Therefore we’ll work with tricks to achieve the appearance we’d like.

      Prerequisites for DHTML What prerequisites do you need for DHTML? First of all: you’ll need a “Version 4” browser. And in order to move objects or make them visible or invisible, you must place them in the proper “containers.” CSS recognizes <span> on the character level and
      on the paragraph level. I’d recommend
      . If you, for example, would like to place a graphic in a
      container, it would look like this:


      Note first that in
      tags, name is completely replaced by id. As a reminder, this attribute serves to access the
      container with JavaScript. With class, you’re specifying the CSS class names, here for the sake of simplicity, also picture1. In the style sheet itself, you would reference these class names using div.picture1 {style properties}. In the style sheet you specify the exact position of the
      container. You do this with the corresponding CSS attributes for the position. Please see page 45 of the reference section for more information. There you’ll find an overview! Our exemplary graphic could be positioned as follows: div.picture1 { position: absolute; top: 80px; left: 800px }

      And now comes the trick: you’ll use JavaScript to manipulate these properties. In the following examples we’ll change the position of movable objects and switch them from visible to hidden.

      Manipulating
      containers with JavaScript How do you address position with JavaScript? How do you switch an object from visible to hidden? Internet Explorer and Netscape go their separate ways here! In Internet Explorer you use the all property of the document object. Here’s the syntax: document.all["picture1"].style.Position

      The Netscape browser, by contrast, uses the layers property. Here’s what you would write: document.layers["picture1"].Position

      All you need to do is place in square brackets the name that you’ve assigned the
      layer with the attribute id. In the example, it’s picture1. Since we’re talking about strings, you need to place them in quotation marks. And what do you put for the placeholder word position? Here’s where the commands to manipulate the JavaScript properties belong: In CSS

      In Internet Explorer

      In Netscape

      left=10px

      pixelLeft=10

      left=10

      top=120px

      pixelTop=120

      top=120

      visibility: visible

      visibility="visible"

      visibility="visible"

      visibility: hidden

      visibility="hidden"

      visibility="hidden"

      This is assuming that you’d like to place an object called picture1 500 pixels from the left-hand side. Then, in Internet Explorer, you’d do the following: document.all["picture1"].style.pixelLeft=500

      And in Netscape, this line would look like this: document.layers["picture1"].left=500

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      DHTML

      71

      The Example: Animating a Graphic Now to our first example. A graphic (airplane.gif) should move from right to left on a straight line through the picture. With this, we’ll create a “timeline effect.” The script will work in Internet Explorer and in the Netscape browser. Given: in Internet Explorer we’d also be able to solve the problem with <marquee>. But in contrast to <marquee>, you can do much more with JavaScript: if you’d like, you can build in sudden stops, a halt, crooked movements, etc. if you use the appropriate routines.

      The source code in brief Let’s just go ahead and have a look at the script in brief. I believe that with your existing knowledge, you’ll be able to comprehend the code quite quickly. Therefore, I’ll only explain the most important parts. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

      Welcome to Butterfly Airlines! <style type="text/css"> <script language="JavaScript" type="text/javascript">
      document.all["picture1"].sty le.pixelLeft=800-i; 18 } 19 if (document.layers) { 20 document.layers["picture1"]. left=800-i; 21 } 22 setTimeout("picturemove()",1 0); 23 } 24 //--> 25 26 27 28

      Welcome to Butterfly Airlines!

      29
      airplane
      30 31

      A counter counts from 0 to 1000. Thereby, the position of the container at the end is set to -200. Only this way will the airplane disappear completely from the picture at the end. Also important is the if statement in Line 16. The command if(document.all) means nothing more than “if Internet Explorer, then …” In Line 19, by contrast, the program addresses the Netscape browser with if(document.layers). The airplane begins its flight in the position 800-0, that is, depending on screen resolution, approximately on the right-hand edge of the screen. Every 10 milliseconds, our function is “refreshed,” so the airplane moves pretty fast to the left. You can make this value larger to lengthen the “flight time.” If the counter arrives at 1000, then we’ve placed the left position at -200. The airplane has disappeared. Did I forget to mention something? Right: you’ll find this example under the name butterfly.htm in the dhtml folder.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      72

      DHTML

      Programming Pull-down Menus with DHTML Have you ever eyeballed the cool pull-down manus on the Microsoft Web site? Wow! Only Microsoft could do something like that. Or maybe not? Now have a closer look at the menus; they aren’t really that cool at all. If you visit Microsoft with Internet Explorer, then everything is perfect. But Microsoft people are known to have a hard heart toward users of the Netscape browser, therefore if you’re viewing their site with Netscape, nothing works. Admitted, it’s quite difficult to accommodate both browser platforms in perfect DHTML. But we’re going to try to do exactly that. The following example works with both browsers since we’ve reached deep into our bag of tricks to make the Netscape browser do what it’s supposed to. Here is the example for this section. After a click on the menu text, the corresponding menu should drop down. Only if you select Close Menu and take the mouse away should the menu fold itself back up.

      What lies behind this? The menus are levels, which at first are displayed in hidden form. Only with onMouseover do they become active. The function that drops them down springs into action. The option Close Menu calls a function that references the hidden attribute for the “level.” If you’d like, you can add more menus. Here is the complete source code for the document. You’ll find it under the name menu.htm in the dhtml folder. 1 2 3 4 5 6

      7

      8

      9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28

      Animation with DHTML <style type="text/css"> <script language="JavaScript" type="text/javascript">
      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      DHTML

      73

      29 30 31 32 33 34 35 36 37 38 39

      if (document.layers) { document.layers[menu].visibility="hidden"; } } //-->

      Pull-down Menus with DHTML

      40 47 54 55

      The source code in brief Here we’re working extensively with style sheets again. This begins in Line 6 with the menu bar. We’ve placed a 20 pixel high and 300 pixel wide image on the page, which is positioned 50 pixels from the top and 20 pixels from the left. The background color should be silver, but since Netscape can’t interpret background, we need to add layer-background-color: silver. In Lines 7 and 8, the menus are positioned. They are given a yellow background. We’ve gauged their size, extent, and position so that they appear in the right position underneath the menu bar. The heart of our project is visibility: hidden. By default, the menus are invisible at first. Lines 9 to 12 take care that our hyperlinks will appear without ugly underlining. I haven’t built a hover effect in since it can’t be interpreted by Version 4.x of the Netscape browser. Understanding the JavaScript portion of this program shouldn’t be difficult. I’m working with two functions, aptly named open() and close(). These are fed the variable menu as a parameter. The function open() makes the selected menu visible (Lines 19 and 22) and the function close() accomplishes the opposite task. Lines 38 and 39 construct “the long menu bar.” Here we’ve built in a “function link,” which just calls the open() function via onMouseover. In the other two
      containers, Lines 45 and 52 take care of closing in case of a “lost mouse.” The many   empty spaces serve as a trick: on the one hand, they arrange the text; on the other, they ensure that Netscape will display the background color across the entire width of the page.

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      DHTML

      74

      Curtain up and ... Butterfly! For the next project, I looked to my television for inspiration. After you’ve turned a television off (by the way – this is a good thing to do!), the picture doesn’t disappear right away. The television bids you goodbye with a “curtain,” the curtain effect. The curtain “pulls itself shut” from left and right, and only then does the tube get its well-earned rest. Yes, the world is going to the dogs! But enough about the television: let’s give “Butterfly Airlines” a bit more pep when making its entrance! Let’s try the opposite of what I’ve described above, namely opening the curtain. Let’s make a real little show. After the curtain opens, nothing will happen for 3 seconds, which will increase the anticipation. After that, a butterfly will fly across the screen for about 7 seconds. Only after this prelude will the familiar document butterfly.htm appear. Here’s the order of the scenes in brief:

      For the curtain effect I need a window with precise proportions. For this, I chose 800 x 600 pixels.

      The pre-switch page start.htm Because of the need for precise window proportions, I’ll first program a “pre-switch page.” From here the actual window will be called up using the window.open() method. In addition, I’ll take care of the exact positioning of the upper left-hand corner of the screen. This is ideal for surfers with inferior screen resolution. window.open("curtain.htm","curtain","width=800,height=600,left=0,top=0");

      The document curtain.htm And now to the “curtain.” curtain.htm takes care of this. But what exactly happens here? First I’ve defined two
      containers called layer1 and layer2. In the style sheet I’ve defined their position exactly. The
      tag with the class pos1 is responsible for the left curtain, which I’ve colored yellow. With pos2 I’m describing the right curtain, which is gray. The trickery for Netscape is important again here. I’ve placed an empty, right-aligned paragraph in this
      container. In here, there is only an invisible, protected empty space ( ):

       

      . Without this trick, Netscape would refuse to display the colors! The rest of the script isn’t any great adventure. With the counter variable i, I’ve made sure that the position will change from the left. In the left curtain, this value becomes negative, in the right curtain, positive. Using setTimeout() to “drive the repetition,” this game will continue until the curtain is open. When the value of the counter variable reaches 400, this function passes control over to the next function. The next setTimeout() method helps us to build in a delay of our choosing; in the example, it’s 3 seconds. The flutter() function manipulates a
      container in which I’ve placed the graphic butterfly.gif. Here the values of left and top are determined by random numbers. And these are refreshed every half second so that you get the impression that the butterfly is “fluttering” around. Here also, a counter variable is at work. When its value reaches 10, location.href passes control to the familiar page butterfly.htm. Animation with DHTML <style type="text/css">
      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      DHTML div.pos3 { position: absolute; visibility: hidden; } //--> <script language="JavaScript" type="text/javascript"> 10) { location.href="butterfly.htm"; return false; } setTimeout("flutter()",500); } //-->

       

       

      Butterfly


      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      75

      76

      Checking JavaScript Code for Errors

      Checking JavaScript Code for Errors Surely it’s happened to you before: you’re “scripting” merrily away and what is the result? An error message. In short: your JavaScript code contains a bug. With “bug,” we’re talking about program errors, not insects. Why? The old computers that were based on relays had to be “debugged” from time to time. Insects had put the mechanical switches out of order. But how do you find and correct errors? The browser itself may be of some help. Just pay attention to the error messages. For example, have a look at the bottom left corner of the screen. In case of a script error, Internet Explorer will display a warning sign.

      Just double-click on this icon. The program will provide you with further details. In the Netscape browser, the error message looks like this:

      You must type javascript:

      into the address line of the browser and press [Enter]. Now the Netscape browser will show you a more complete error message. In the lower portion of the window, you’ll even find a debugging console, which you can use to test out commands in advance.

      Internet Explorer’s debugger Most interesting is the built-in “debugger” for Internet Explorer. It is truly a joy for programmers since it provides them with an actual development environment. But you don’t see any command for debugging? Choose TOOLS/INTERNET OPTIONS in Internet Explorer. Now have a look at the ADVANCED tab. Remove the checkmark next to DISABLE SCRIPT DEBUGGING and click APPLY. It’s also possible that you’ll need to reinstall the program. In Windows, select START/SETTINGS/CONTROL PANEL. Double-click on ADD/REMOVE PROGRAMS. Here you can “complete” installation of Internet Explorer by adding this debugger. In Windows 2000 you’ll find the script debugger in WINDOWS COMPONENTS. But don’t expect all that much from the debugger. The program won’t always find the exact point at which you’ve made a mistake! Therefore, you should always check to see whether you’ve forgotten a dot, a comma or a semicolon. Just a little error can make for many hours of frustration!

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      Index

      77

      Index {}, 27 1st Page, 12 absolute positioning, 67 alert(), 17 Anchors, 60 Arrays Abbreviation, 47 overview, 47

      Background graphics in CSS, 67

      Banner, 96 bgColor, 33 Borders and frames in CSS, 66

      Browser redirection, 21 Bug, 114 Buttons, dynamic, 93 Calculation, 19 CGI, 85 Changing background colors, 25 Changing text, 80 Changing the background color, 33 Character sets, 69 Colors, 67, 69 Comments, 16 Comparison operators, 23 confirm(), 88 Cookies, 98, 100 Counter variable, 27 CSS, 63 Curtain effect, 108 Date, 50 Decision making, 25 DHTML absolute positioning, 67 Animating a graphic, 104 Curtain effect, 108 Problems, 103 Pull-down menus, 106 Überblick, 103

      Dice game, 45 Document type definition, 10 DTD, 10 dynamic buttons, 93 E-Mail addresses Checking for validity, 91

      Errors in JavaScript, 114 Event Handlers, 31 focus(), 90 font tags, 56

      for loop, 27 Form Evaluating, 85

      FormMail, 85 Forms Calculating, 92 Checking e-mail addresses, 91 Checking form field entries, 89 in XHTML, 58 Order form, 86 Password check, 89 Reset, 88 Submit, 88 Testing zip codes, 90

      Frames changing several frames, 76 forcing a page into a frameset, 79 freeing pages from a frameset, 79 Hierarchy, 78 in XHTML, 61 Pull-down menu, 73

      Functions calling, 32 Overview, 31 with parameters, 33

      Graphics adding, 55

      Headings, 55 Hover graphics, 93 Hover links, 70, 95 HTML converting to XHTML, 12 Reference, 53 Syntaxcheck, 12 versus XHTML, 9

      HTML Kit, 12 HTML TIDY, 12 Hyperlink starting JavaScript, 32

      Hyperlinks in XHTML, 60

      id, 9 Idiosyncrasies, 14 If statement, 23 Java, 14 JavaScript Calculation, 19 Comments, 16 Date and time, 50 Evaluating forms, 88 Finding errors, 114 Functions, 31 Incorporating music, 48 integrating, 15 Mathematics, 45

      starting with buttons, 31 versus Java, 14 with a Hyperlink starting, 32

      Jukebox, 48 Lines, 56 Lists, 56 Lists in Style Sheets, 65 Looping for, 27 while, 29

      marquee, 57 Math, 45 Math.random, 45 Math.round, 45 Mathematical operations, 19 Mathematics, 92 MathML, 7 Methods, 14 moving text, 57 Music Adding to XHTML, 57 incorporating, 48

      name, 9 Objects, 14 onBlur, 90 onClick, 31, 32 onLoad, 32 onMouseOver, 32, 93 onUnLoad, 32 parent, 78 Passing parameters, 33 Password Check in Forms, 89 Password protection with if, 23 with switch, 25 with while loops, 29

      Perl, 85 prompt(), 17 Pull-down menu in a frameset, 73 with Go button, 71 with onChange, 73

      Pull-down Menus in JavaScript, 71 with DHTML, 106

      Random links, 47 Random number, 45 Redirection, 21 Reset, 88 select(), 90 Servicepage, 4 setMonth(), 100 setTimeout(), 21 SMIL, 7 Special characters, 69

      © Johann-Christian Hanke and KnowWareGlobal.com - 17-01-01

      string, 82 Style Sheets absolute positioning, 67 Borders and frames, 66 Reference, 63 Text alignment, 65

      Submit, 88 substring(), 83 switch, 25 Syntaxcheck, 12 Tables, 60 Ticker overview, 80 using the string object, 82

      TIDY, 12 Time, 50 Timeline effect, 104 Timer, 21 toGMTString(), 100 Units of measurement, 69 Variables, 17 W3C, 6 while loops, 29 XHTML Adding graphics, 55 Adding music, 57 Basic structure, 10 coverting from, 12 Differences from HTML, 9 Forms, 58 Frames, 61 General Tags, 53 Hyperlinks, 60 Lines, 56 Lists, 56 Reference, 53 simple text formatting, 55 Tables, 60

      XML Advantages and Disadvantages, 7 Overview, 6

      XSL, 7

      Related Documents

      The New Standard
      November 2019 10
      The New Standard Menu
      June 2020 6
      Exploring The Xhtml Dtd
      December 2019 16

      5
      Number