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.
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
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.
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 ExpertsMichael Maardt <price>$4.95 Homepages for BeginnersJoh.-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.
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
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!
Ö 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.
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.
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.
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.”
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
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.
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 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”.
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
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
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.
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!
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!!!
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!"); }
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.
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">
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.
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: backforwards
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.
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.
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); } //-->
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.)
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!
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>Contents<\/body><\/html>") win.document.close();
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.
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.
The screen Object The so-called screen object is on center stage here: Property
returns
Example of output
screen.height
Height of the screen in pixels
600 or 768, etc.
screen.width
Width of the screen in pixels
800 or 1024
screen.availHeight
Visible screen height in pixels
572 or 740
screen.availWidth
Visible screen width in pixels
780 or 1010
screen.colorDepth
Color depth
8, 16, or 32
navigator.platform
Operating system
Win32 or MacPPC
navigator.appName
Browser name
Microsoft Internet Explorer or Netscape
navigator.userAgent
Exact browser designation
Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)
navigator.language
Language
de, en, es (Spanish), fr (French), da (Danish), etc. Only works with Netscape 4 and above, not with Internet Explorer!
And what can you do with this? Read out the information and react to it. The best-known example is the famous „Browser Question.“
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!"); }
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.
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
and ends with
. The attribute border="1" takes care of the border lines. The individual lines are enclosed in the tags
. The tags
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:
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
Seeking Information <script language="JavaScript" type="text/javascript"> Information<\/title><\/head>"); showwin.document.write("
"); showwin.document.write("
Screen height<\/td>
" + high + " Pixel<\/td><\/tr>"); showwin.document.write("
. 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.
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!
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.
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.
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.
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>"); datewin.document.write("Today is " + weekday[day] + " " + monthname[month] + " " + date + ", " + year + "!"); datewin.document.write(" It is exactly " + hour + ":" + minute + " O’Clock.<\/b>"); datewin.document.write("
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!
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.
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. 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
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
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
Cats
value
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)
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;
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
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
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
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 1
Cell 2
Cell 3
Cell 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”
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.