* Table Attributes
2. HTML FORMS 36
* Introduction to forms
* The FORM element
* Controls
* The INPUT element
* The BUTTON element
* The SELECT and OPTION elements
* The TEXTAREA element
* Labels
* The LABEL element
ADVANCED HTML 46
1. Image Maps 47
* Working with Image Maps
* Server-Side Image Map
* Client -Side Image Map
2. Frames and Windows 49
* Introduction To Frame
* Syntax
* Creating a Window
3. Cascading Style Sheets 55
* Introduction To Style Sheet :
* Adding style to HTML
* Setting the default style sheet language
* Inline style information
* Header style information :the STYLE element
* Inheritance and cascading
Contents (contd ...)
LEARNING JAVASCRIPT : PART I 62
* What is Javascript ?
* JavaScript Vs CGI
* JavaScript Vs Java
* Javascript Basics through Examples
* Why JavaScript is Easy:
* Why JavaScript is Important for Web Dev.
* What is the Disadvantage of JavaScript
* Write Your First JavaScript
* Javascript, "Dynamic HTML" and Style Sheets
LEARNING JAVASCRIPT : PART II 79
LESSON 1 79
1. Introduction to Window Manipulation
2. Window Manipulation in JavaScript
3. Examples of Opening Windows with JavaScript
4. Windows Features
5. The JavaScript Document Object Model
6. Messing with the Status Bar
7. Communicating between Windows
8. More about the JavaScript Document Object Model
9. Other Properties of Windows
10. More about Window and Frame Hierarchies
LESSON 2 88
1. Looping Password
2. More about While Loops
3. Nested Loops
4. Arrays and Loops
5. Arrays in the Document Object Model
6. Functions
7. Functions with No Parameters
8. Parameters and Return Values
9. Functions with More Than 1 Parameter
10. Function Program
11. Review
LESSON 3 105
Introduction to Forms
1. Text Field Events
2. Form Handlers
3. Review
INTRODUCTION TO HTML
Briefing
Writing documents for the Internet
The HyperText Markup Language is the standard format for hypertext documents being served by World-Wide Web servers. It works by including tags surrounding the text within a document which dictate such things as the style and size of the body of text, the background color or they may indicate links to other documents and other types of resources available on the Web. For those unfamiliar with use of HTML composing documents can be both problematic and time consuming.
* There is the task of finding information on HTML itself. Many on-line references and primers are easily accessible on the Web, but currency, completeness and clarity in documentation are some factors that complicate the process.
* For users not familiar with a markup language, the whole framework may be unfamiliar as well. Even when armed with documentation and an idea of how HTML is structured, it is often necessary to expend considerable time reformatting a document to achieve the desired result.
* Even if the user does not find the HTML markup codes difficult to understand, they are cumbersome to type in and lend themselves to easy mistakes, such as forgetting a backslash in a closing tag.
* Overall, it is very time consuming to compose documents when compared with composition through use of a familiar page layout or word processing application.
There are several editors which make the job of creating HTML documents easier. Most of them allow you to hilite a text block and apply the proper tags on either side of the block. The more advanced have intelligent markup, templates, error checking, and even WYSIWYG viewing (usually by dumping the file to a WWW client). Some also add much needed support for maintenance of an entire site and for easy updating of file batches.
But the available software by no means offers a panacea. The current state of HTML authoring programs leaves much to be desired for people interested in creating and managing multiple-page Web sites. Many programs don't include necessary features and others are still in beta, making potentially useful features too slow or quirky for serious authoring. Even so, several of these programs have a great deal to offer to anyone wanting to make a few Web pages without memorizing lots of tags and attributes. In the coming year, I expect we will see an explosion of Web authoring tools and an increase in the quality of the tools.
Useful criteria for evaluating HTML Editors
* What tags are supported - HTML 2.0, HTML 3.0, Netscape Extensions?, etc
* Does a new document template provide the HTML, HEAD, TITLE, BODY tags which are essential to an HTML document?
* How are tags accessible - through pull-down menus, dialog boxes, toolbars?
* Does the editor provide detailed help files for all of its components?
* Does the editor support tables, forms, CGI scripting, JavaScripting
* Does the editor have spell checking capabilities?
* How easy is it to create links to documents on the WWW?
* How easy is it to create links within your own document?
* How easy is it to insert images into the HTML document?
* Does the editor have a preview feature to allow off-line viewing of the HTML document?
BASIC HTML
1. Terms and Concepts
* Assumptions
* Terms
* Your Web Browser
* Writing To The Norm
* HTML: Behind the Scenes
2. Document Tags
* HTML
* HEAD
* TITLE
* BODY
* Comment Tags
3. Basic Text Structures
* Headings
* Paragraph
* Line Break
* Blockquote
4. Lists
* Unordered Lists
* Ordered Lists
* Definition Lists
5. Special Effect Tags
* Logical Tags
* Style Tags
* Horizontal Rule
6. Anchors
* HREF
* NAME
7. Images
* IMG
* ALIGN
* ALT
* Getting the Right Format
Chapter 1 : Terms & Concepts
Assumptions
In the writing of this document, I have made certain assumptions which I should state clearly. The first is that you are using a graphical web browser such as Netscape, InternetExplorer, etc., and not a character-based browser such as Lynx. I have tried to keep my explanations and examples as "universal" as possible, but I make no guarantees as to this.
The second is that you are somewhat familiar with the operation of a Web browser and have already visited several Web sites. If this is not the case, you should do so before starting this material. If you're looking for something which will explain various terms you've seen or heard, try to get it from "Beginner's Web Glossary".
The third thing is that when I talk about text, or content, or things of that nature, I am generally not referring to what appears in the Web browser. I am talking about what is in the actual HTML file. There can be a big difference; make sure you know what we are talking about. If you can't make heads or tails of it, let me know there's a problem.
Terms
There are a few common terms which we will use again and again. we'll just quickly define them here.
Content
The actual 'meat' of a document -- all of the words, images, and links
which a user can read and interact with. I use this term a lot to mean
"whatever you put in the document."
Hyperlink
A link from one document to another, or to any resource, or within a
document. For example, just above where its says "Beginner's Web
Glossary" and that text is highlighted in some fashion. The default is
usually blue, underlined text, but your display may vary.
In-line
Almost always used in the context "in-line image," this refers to a
resource of some type which is placed directly into a document. As I
say, this is nearly always an image, but the future could see things
like in-line animations.
URL
The Uniform Resource Locator is a "standard" way of easily expressing
the location and data type of a resource. URLs in general take the
form "protocol://address" where protocol is something like gopher,
FTP, telnet, and so on, and the address is merely the server and
pathname (if any) of a given resource or page. For more information,
take a look at the Beginner's Guide to URLs at the National Center for
Supercomputing Applications (NCSA).
Your Web Browser
The part of your Web browser I'll mention most often is the browser display window (also the display window or browser window). This is the part of the Web browser where the actual contents of an HTML document are displayed.
The other thing I'll mention is the history list (sometimes called the go list). That's the list of pages you've visited during the current session. In most browsers, it is available as either a menu or a pop-up dialog box.I think that you are using the latest browser,because sometimes it is possible that some tags are not supported by old browser.
Writing to the Norm
No, not the fat guy on "Cheers." Actually, it's a fundamental issue every Web author needs to know about and appreciate.
Web browsers are written by different people. Each person has their own idea about how Web documents should look. Therefore, any given Web document will be displayed differently by different browsers. In fact, it will be displayed differently by different copies of the same browser, if the two copies have different preferences set.
Therefore, you need to keep this principle foremost in your mind at all times: you cannot guarantee that your document will appear to other people exactly as it does to you. In other words, don't fall into the trap of obsessively re-writing a document just to get it to "fit on one screen," or so a line of text is exactly "one screen wide." This is as pointless as trying to take a picture that will always be one foot wide, no matter how big the projection screen. Changes in font, font size, window size, and so on will all invalidate your attempts.
On the other hand, you want to write documents which look acceptable to most people. How? Well, it's almost an art form in itself, but my recommendation is that you assume that most people will set their browser to display text in a common font such as Times at a point size of somewhere between 10 and 15 points. While you shouldn't spend your time trying to precisely engineer page arrangement, you also shouldn't waste time worrying about how pages will look for someone whose display is set to 27-point Garamond.
HTML: Behind the Scenes
HTML is composed of tags. HTML tags are always enclosed in angle-brackets ( < > ) and are case-insensitive; that is, it doesn't matter whether you type them in upper or lower case. I almost always use upper case, because it makes the tags easier to pick out in a document, but that's just me. You can do whatever you like.
Tags typically occur in begin-end pairs. These pairs are in the form
<tag> ... </tag>
where the <tag> indicates the beginning of a tag-pair, and the </tag> indicates the end. (The three dots indicate an arbitrary amount of content between the tags.) The usual way to refer to each tag is "tag" for the first and "slash-tag" for the second, where tag is the actual name of the tag being discussed.
These pairs define containers. Any content within a container has the rules of that container applied to it. For example, the text within a "boldface container" would be boldfaced. Similarly, paragraphs are defined using a "paragraph container."
Thinking of tag-sets as containers will help in another way: it will help you remember that tags should always be balanced. In other words, you should keep containers nested within each other, just as you would have to do in the real world.
Why should you worry about this? Well, if you start overlapping containers as shown on the right, about the best you can expect is that the document will be formatted in unexpected ways.
One more thing to keep in mind with regards to containers. Since HTML is based on these structures, it is often the case that the arrangement of text within a container is irrelevant. For example, within a paragraph container, all of the text can be in one long line, or in a series of separate lines, or with every word on its own line, or with every word separated from every other by nineteen spaces. These would all be displayed exactly the same.
Therefore, try to keep in mind this thought: whitespace doesn't matter. (Whitespace is all of the blank areas in a text file--empty lines, extra spaces, and so on.) I'll mention this again when discussing the paragraph tag, and it will crop up in other places. Again: whitespace doesn't matter.
Having said all that, I will now attempt to muddy the waters a bit by mentioning that not every tag in HTML is paired. Some tags, such as the line-break tag, stand on their own (that is, they have no closing tag). These are known as empty tags. As we encounter them, I'll point them out.
All Right Already!
Okay, okay, no more conceptual overviews -- for now. At certain points, I'll go off on a tangent related to whatever tag is being discussed. They'll be relevant tangents, but tangents nonetheless. I'll mark these with the following symbol:
When you see one of those, you'll know that I'm taking time out to discuss something other than the actual mechanics of HTML. These could be design tips, browser issues, or anything else.
Chapter 2 : Document Tags
By "document tags," I mean the tags which divide up a Web page into its basic sections, such as the header information and the part of the page which contains the displayed text and graphics. This may seem confusing right now. Just hang on.
HTML
The first and last tags in a document should always be the HTML tags. These are the tags that tell a Web browser where the HTML in your document begins and ends. The absolute most basic of all possible Web documents is:
<HTML>
...
</HTML>
That's it. If you were to load such a page into a Web browser, it wouldn't do anything except give you a blank screen, but it is technically a valid Web page. Obviously, you'll want more than that.
HEAD
The HEAD tags contain all of the document's header information. When I say "header," I don't mean what appears at the top of the browser window, but things like the document title and so on. Speaking of which...
TITLE
This container is placed within the HEAD structure. Between the TITLE tags, you should have the title of your document. This will appear at the top of the browser's title bar, and also appears in the history list. Finally, the contents of the TITLE container go into your bookmark file, if you create a bookmark to a page.
What you type should probably be something which indicates the document's contents, but it doesn't have to be. The length of the title is pretty much unlimited, but don't go overboard. Users will either sneer at or be confused by exceedingly long titles.
If you don't type anything between the TITLE tags, or don't include the TITLE tags at all -- remember the blank document in the HTML section earlier? -- then the browser will typically use the actual file name for the title. Therefore, a document titled "TCh4ex4.html" will have that name appear in the history list. Again, you can choose to do this, but it will likely generate either confusion or contempt.
You should only have one TITLE container per document. At one point, it was possible to create "dancing titles" by including multiple TITLE tags. Not only is this a savage abuse of HTML, but the effect can only be seen in certain versions of certain browsers. Therefore, it should be avoided at all costs.
BODY
BODY comes after the HEAD structure. Between the BODY tags, you find all of the stuff that gets displayed in the browser window. All of the text, the graphics, and links, and so on -- these things occur between the BODY tags. We'll get to what happens there starting with the next chapter.
So, putting everything we've covered thus far into one file, we have:
<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>
...
</BODY>
</HTML>
This time, the result would be a document with a completely blank browser window, but at least the words "Document Title" would appear in the browser's history list. But don't take my word for it -- look for yourself.
Let's look at the above block of HTML again, but this time with container lines sketched in. Note that the TITLE tags and text have been rearranged to make it easier to draw in the container lines. The rearrangement of the text does not in any way change the resulting Web page's appearance.
Figure: A basic HTML document with container lines drawn to show the document's structure.
Comment Tags
If you want to leave yourself notes in an HTML document, but don't want those notes to show up in the browser window, you need to use the comment tag. To do that, you would do the following:
<!-- Hi, I'm a comment. -->
Your note would go where the text Hi, I'm a comment. appears. Yes, you do need an exclamation point after the opening bracket, but not before the closing bracket. That's the way the standard is written. I have no idea why. Also, there is no end tag; that is, a tag like </!-- text --> does not exist. The comment tag is not a container. This is our first example of an empty tag.
You can put comments pretty much anywhere, but you have to be aware of one important thing: you shouldn't put any HTML markup within a comment tag. Theoretically, you should be able to, but most browsers handle this less than gracefully (i.e., they either mess up or crash).
What if you get the tag wrong, like forgetting to include the exclamation point? In that case, the text you did type in would be displayed. See for yourself, and then take a look at the same thing with correct markup (the exclamation point was put back in). Hooray, another totally blank page!
Yawn...
Okay, so you're tired of doing things which end up as blank browser windows. Same here. That means it's time to move on to the next chapter, where we'll start building up your knowledge of HTML. By the time we're done, that knowledge will include everything you'll need to create your very own Web documents!
Chapter 3: Basic Text Structures
All right, we know how to set up a document, but all we've gotten so far has been dull, blank browser windows. Time to fix that.
You'll remember that I discussed the way tag-pairs are used to create containers in which content is held and certain rules applied to it; in short, the structural nature of HTML. We've already seen some of that in the way a Web document is split into two main sections: the document's header and body. In this chapter, we're going to get into some of the structures within the BODY.
Headings
The heading structures are most commonly used to set apart document or section titles. For example, the word "Headings" at the beginning of this section is a heading. So is this document's title (it's at the top of the page, in case you somehow missed it).
Remember that these heading structures go into the body of the document. The headings being discussed here have nothing to do with the HEAD structure from the previous chapter.
There are six levels of headings, from Heading 1 through Heading 6. Heading 1 (H1) is "most important" and Heading 6 (H6) is "least important." By default, browsers will display the six heading levels in the same font, with the point size decreasing as the importance of the heading decreases.
Here are all six HTML pairs, in descending order of importance:
<H1>Heading 1</H1>
<H2>Heading 2</H2>
<H3>Heading 3</H3>
<H4>Heading 4</H4>
<H5>Heading 5</H5>
<H6>Heading 6</H6>
These six lines, when placed into an HTML document, will simply display the six levels of headings. Take a look.
Since, as we have discussed, whitespace doesn't matter, you might think that the above block of HTML would just string the content into one line of text. However, because headings are meant for section titles and the like, they are defined as existing on a line by themselves. A heading always begins at the margin of a line and always forces a line break at the end of the heading. In other words, you cannot have two heading levels on the same line.
This also means that you cannot highlight text in the middle of a paragraph by marking it as a heading. If you try this, the paragraph will be split in two, with the heading text on its own line between the two pieces. (Later on, we'll talk about ways of highlighting text.)
If you have a browser which is set close to its default settings, you'll notice that the text for the last two headings gets pretty small. This leads to some page designers using H6 for the fine print at the bottom of pages. This is a mistake, not to mention an abuse of the heading structure. As you no doubt know, many browsers allow the user to set the size of each element, including the headings. If a user sets H6 to a size of 18 point, the fine print won't be so fine any more!
Remember: you cannot guarantee that your document will appear to other people exactly as it does to you.
Paragraphs
As you might suspect, paragraphs are quite common in Web pages. They are one of the most basic structures in HTML. If you regard a document as a collection of structures and sub-structures, you may come up with something like:
The overall structure is a page. The page is composed of a number
of sections, each of which is composed of one or more paragraphs.
Each paragraph is composed of words, and each word of letters.
Admittedly, this is a simplified way of looking at text, but it will do for our purposes. The furthest HTML goes down this progression is to the paragraph level.
The beginning of a paragraph is marked by <P>, and the end by </P>. This material is obviously filled with examples of this container.
Let's say you want to create a paragraph. You start to wonder, "What happens if I hit return at the end of every line in the paragraph? Should I make the paragraph just one long continuous line? What if I accidentally put too many spaces between words?"
At this point, you should once again be saying to yourself: whitespace doesn't matter. You could put each word on its own line, and the paragraph would look completely normal. In fact, no matter how much whitespace you put between words, whether returns or spacebar hits, the words will be separated by one space in a Web browser.
Got all that? If you're not sure you completely understand, go through the section again -- or better still, try it on your own.
Line Break
So what if you want to end a line after a certain word, but don't want to start a new paragraph? Well, what you need is a line break, which is invoked by using the <BR> tag. This forces a line break wherever you place it in the content (that is, whatever is after the <BR> tag will start from the left margin of the next line on the screen.)
And no, there is no </BR> tag. The line break tag is -- that's right! - an empty tag. And when you think about it, this makes sense. The concept of a line break beginning and ending doesn't really work, since a line break is a one-shot occurrence.
Blockquote
Blockquotes are handy for those long pieces of text which are quoted material and therefore need to be set apart and indented. That is exactly what blockquote does. For example:
This section of text is surrounded by the blockquote tags. A
blockquote can exist inside of a paragraph, and always lives on
its own line (which is to say, there is an implied line break
before and after the blockquote, just as with headings or
paragraphs themselves).
Blockquotes are set up as follows:
<blockquote> ...text... </blockquote>
Just like most other things in HTML, it's a container.
List:
There are three main types of lists. I've included the heading here because lists are basic text structures -- they just need a lot more explanation. That's what you'll find in the next section.
Chapter 4: Lists
While simple in concept, lists can be very powerful in execution. There are three types of lists: unordered lists, ordered lists, and definition lists. The first two are very similar in structure, while definition lists have a unique setup.
Unordered Lists
The term "unordered list" may be a bit unfamiliar to you, but odds are you've heard of the "bullet list." That's exactly what an unordered list is -- a list of items, each one preceded by a "bullet" (a distinctive character; typically, a small black circle).
The list begins and ends with the tags <UL> and </UL> respectively. Each item in the list is marked using the <LI> tag, which stands for "List Item." <LI> has a corresponding </LI>, but this closing tag is not required to end the list item (although you could use one if you really wanted to). You can use as many list items as you like, up to your browser's built-in maximum, if any.
Here's the markup for a simple list:
<UL>
<LI>Monday
<LI>Tuesday
<LI>Wednesday
<LI>Thursday
<LI>Friday
<LI>Saturday
</UL>
If you loaded an HTML page containing the markup above, you would see the days of the week, each one preceded by a "bullet." To wit:
* Monday
* Tuesday
* Wednesday
* Thursday
* Friday
* Saturday
Almost anything can be put into a list item -- line breaks, entire paragraphs, images, links, or even other lists. For example(a nested List):
<UL>
<LI>Monday
<LI>Tuesday
<LI>Wednesday
<UL>
<LI>6am - 9am
<LI>9am - 12n
<LI>12n - 3pm
<LI>3pm - 6pm
</UL>
<LI>Thursday
<LI>Friday
<LI>Saturday
</UL>
In the above case, under "Wednesday" in the 'outer list,' you would find another unordered list (the three-hour blocks of time), which is referred to as a nested list. (In the markup above, I have indented the nested list for purposes of clarity; this is not required for the lists to work.
Remember what I've said about whitespace...) Here's how it looks:
Monday
Tuesday
Wednesday
* 6am - 9am
* 9am - 12n
* 12n - 3pm
* 3pm - 6pm
Thursday
Friday
In theory, you could probably nest lists indefinitely, but a bit of restraint is called for. Don't nest them too deeply unless you absolutely have to, if for no other reason than aesthetics. Nesting lists too far can look pretty bad.
Ordered Lists
On the face of it, ordered lists look a lot like unordered lists, and a lot of the same rules apply to both constructs. The only difference in HTML is that instead of using <UL> and </UL>, an ordered list is contained within the tags <OL> and </OL>. Ordered lists are based on list items, just as unordered lists are.
However, when an ordered list is displayed in a Web browser, it uses an automatically generated sequence of item markers. In other words, the items are numbered. The markup for a simple ordered list, based on the first example in this chapter:
<OL>
<LI>Monday
<LI>Tuesday
<LI>Wednesday
<LI>Thursday
<LI>Friday
</OL>
The above markup will look similar to the previously discussed simple unordered list, with the important difference that each day of the week is numbered instead of preceded by a "bullet." In other words, it looks like this:
1. Monday
2. Tuesday
3. Wednesday
4. Thursday
5. Friday
Ordered lists are as nestable as unordered lists, and you can nest unordered lists in ordered lists, as well as the other way around. This can get pretty complicated, but sometimes it's what you need.
Definition Lists
As you might expect, definition lists begin and end with the tags <DL> and </DL>. However, unlike the unordered and ordered lists, definition lists are not based on list items. They are instead based on term-definition pairs.
Here's the markup for a basic definition list:
<DL>
<DT>Do
<DD>a deer, a female deer
<DT>Re
<DD>a drop of golden sun
<DT>Mi
<DD>a name I call myself
<DT>Fa
<DD>a long, long way to run
<DT>Sol
<DD>a needle pulling thread
<DT>La
<DD>a note to follow so
<DT>Ti
<DD>a drink with jam and bread
</DL>
A good way to think of it is that <DT> stands for "Definition-list Term" and <DD> stands for "Definition-list Definition." When the above list is displayed, it arranges the elements such that each term is associated with the corresponding definition. The exact arrangement of elements may vary from browser to browser. Here's how the above markup comes out:
Do
a deer, a female deer
Re
a drop of golden sun
Mi
a name I call myself
Fa
a long, long way to run
Sol
a needle pulling thread
La
a note to follow so
Ti
a drink with jam and bread
Similar to ordered and unordered lists, definition lists can be arbitrarily long. Almost any structure can be placed in a <DD> tag, but putting large-scale structures (such as paragraphs, headings, and other lists) in the <DT> tag is not legal, according to the HTML Specification 2.0. You can leave out one part of a DT-DD pair, but this is not recommended.
Definition lists are perfect for creating glossaries. For example, the Beginner's Web Glossary on our server is simply one relatively long definition list.
There is one attribute to the <DL> tag, which is compact. This causes the display of the definition list to be compacted. What does that mean? It means that the information contained in the <DD> will be displayed on the same line as the <DT> term, if possible. (By the way, Microsoft's Internet Explorer does not support this attribute, so the examples in this section aren't going to work if you're using Explorer.) The markup would start out:
<DL compact>
<DT>Do
<DD>a deer, a female deer
<DT>Re
<DD>a drop of golden sun
.....
...and the entire compacted list would look a bit different than the first definition-list example. Thus:
Do a deer, a female deer
Re a drop of golden sun
Mi a name I call myself
Fa a long, long way to run
Sol a needle pulling thread
La a note to follow so
Ti a drink with jam and bread
Pretty neat, eh? One word of warning, though: this will only work when your terms are short enough to allow the definition to appear on the same line. If the term is too long, the definition will start on the next line, just as they would in an uncompacted list. Here's an example:
1. The first part of the second clause shall be, in case of tort appeal,
herewith known as "Oscar," unless it is Tuesday, in which case...
Section II. Non-corporeal entities
In the case "Beckwith v. Snuffleupagus" it was shown that the claimed
existence of a normally invisible being does not in and of itself
constitute evasion or fraud...
In the first case, the term "1." is so short that there is no problem with starting the definition on the same line as the term. In the second case, however, since the term is so long, the definition is forced to start on the next line.
In the next chapter, we'll see out how to spice up text even more by using what I refer to as "special-effect" tags.
Chapter 5: Special Effect Tags
You may recall that in Chapter 3, I made a point about using headings to emphasize text within a paragraph. (For those of you who missed it, the point was that you can't use headings that way.) I also promised to show you how to highlight text. That's what this chapter is about, among other things.
Logical Style Tags
The "correct" way to highlight text is to use the logical tags, which do not directly specify the type of highlighting they will employ. There are 'defaults' written into the specification (see the quotations below) but there is no direct rule about which tag should be displayed in what way. This is entirely in keeping with HTML's structural nature.
Emphasis
To quote from the HTML 2.0 specification, the <EM> and </EM> tags
provide "typographic emphasis, typically italics."
Strong
Again from the specification, the <STRONG> and </STRONG> tags provide
"strong typographic emphasis, typically bold."
Citation
<CITE> and </CITE> specify a citation; this includes information like
book titles, references, and so on. The text is usually displayed
using italics.
These tags are recommended for use because they leave the most control to the reader of a document. However, in the real world, the tags in the next section are a lot more popular than those above.
Forced Style Tags
The tags I will cover here are sometimes called forced style tags, because their very nature forces a certain style within the document (at least, that's the idea). This does run counter to the entire "HTML is purely structural" philosophy, but my advice is not to worry about it too much. As long as you use the logical style tags where appropriate, then you're fine.
The four most commonly used forced style tags are very simple:
Boldface
Everything between <B> and </B> is boldfaced.
Italics
Everything between <I> and </I> is italicized.
Underline
Everything between <U> and </U> should be underlined; however, see the note below.
Typewriter Text
Everything between <TT> and </TT> is in typewriter text (a monospaced font in most browsers). This is typically used for variable names, or to show snippets of HTML.
The HTML 2.0 Specification does allow the mixing of these styles, but does not require that a consistent appearance be maintained. In other words, different browsers will display combined styles differently. Some will pick one or the other style, others will not display either, and a few will simply crash.
In some browsers, especially Netscape up to 1.12/1.22, the underline tag is not recognized. This is because the underline tag is still being proposed for inclusion in the HTML specification. As of this writing, it was still not part of official HTML 2.0 but part of the 3.0 draft. Most browsers do support underlining, but be aware that you cannot count on this. If the word "underlined" in the explanation for Underline, above, is in fact not underlined, then your browser does not support the underline tag.
Horizontal Rules
The horizontal rule is a pretty useful effect. Horizontal rules are not allowed within headings. The tag, which is empty, is <HR>, and produces the following:
This is a quick, nearly painless way of throwing in a section divider. In the past, this effect could only be achieved using an in-line image, which just slows everything down (consider the difference in size and download time between a 1K graphic and four text characters).
There. That was pretty easy, wasn't it? Now that you have everything you need to arrange your text, it's time to start linking things together.
Chapter 6: Anchors
The real point of the Web, of course, is that documents can be linked to each other, or to other types of files such as movies or sound clips, through the use of hyperlinks. These links allow authors to link documents together in intuitive ways, as opposed to traditional linear texts such as books, articles, or almost anything else printed.
In order to create a hyperlink, you'll need to know two things. The first is the URL -- that is, the location -- of the file to which you want the link to go. (If you are unclear as to how URLs work, take a look at NCSA's A Beginner's Guide to URLs.) The second is knowledge of how links work, which is the subject of this chapter.
The Basic Anchor
The simplest possible anchor starts with <A> and ends with </A>. However, you will never ever use the <A> tag by itself, because it doesn't do anything. You'll need to enhance the <A> tag with attributes like...
HREF
HREF stands for "Hypertext REFerence," which is another way of saying, "The location of the file I want to load." Most anchors are in the form <A HREF="URL">, where URL is the location of the resource to which you want the link to point. For example, the HOTMAIL Web server is at "http://www.hotmail.com/" (that's the server's basic URL). A sentence which contained a link to that address would look something like:
Check out the <A HREF="http://www.hotmail.com/">HOTMAIL Web server</A>--
it's pretty cool!
The words between the open and close of the anchor ("HOTMAIL Web server") would be displayed as a hyperlink. Selecting that link within a Web browser would cause the browser to load the HOTMAIL Web server's main page. Here's
what the above markup looks like in your browser:
Check out the HOTMAIL Web server-- it's pretty cool!
The double-quote marks found around the value of HREF in an anchor are, under certain specific circumstances, optional. However, in most cases they are required. In addition, if you start the URL with a double-quote, you must close it with another. Just as tags need to be balanced, quote-marks do too. I personally recommend the use of the double-quotes, because it's a good habit to get into, especially when it comes to named anchors (below). Besides, in most cases they'll be required, so just go ahead and use them all the time.
A URL (and therefore, by implication, an anchor) can point to any resource available on the Web. This is usually another HTML page, but it can also be a graphic, a sound file, a movie, or any other kind of file. This fact lets you set up links to large graphics without actually having to display them in the page. For example, if there were a graphic file called "welcome.gif" in the directory "emeyer" of a server with the address "www.site.edu," the URL would be:
http://www.site.edu/emeyer/welcome.gif
Therefore, a text anchor referring to this graphic file would look something like:
<A HREF="http://www.site.edu/emeyer/welcome.gif">See my welcome message!</A>
A user who selects the anchor thus created will cause his Web browser to download the graphic file, which will then be displayed by his browser or by a helper program. The same general principles hold true for referring to sound files, movie files, multimedia files, and any other non-HTML files. So if I wanted to refer to a sound file called "welcome.au" in the same directory as the welcome graphic, I might set up a link like this:
<A HREF="http://www.site.edu/emeyer/welcome.au">Hear my welcome message!</A>
In case you were wondering, the first four letters of a Web URL do mean something. http stands for "HyperText Transfer Protocol," which is the technical way of saying "how the computers move Web data back and forth."
Well, all this is fine for linking between files, but what about jumping around within a document? Glad you asked.
NAME
Using the NAME attribute, you can invisibly mark certain points of a document as places that can be jumped to directly, instead of loading the document and then scrolling around to find what you're after. This is accomplished by using a named anchor, which is slightly different than the anchor used to create a hyperlink.
Setting a named anchor is done using the form <A NAME="label"> ... </A>,
where label is any text you care to use. It could be anything from chapter1
to 2.4.1 to oscar-the-grouch. So putting a name of pt.3 to the text
"Part3: Bagels and You" would be accomplished like this...
<A NAME="pt.3">Part 3: Bagels and You</A>
...and would look like this:
Part 3: Bagels and You
Note that there is no obvious, visible way to tell that the text has been named. This is as it should be. The only way named anchors are important is if they're referred to somewhere else. Also note that the HREF attribute does not appear in this anchor. It can do so, but it is not required; the only requirement is that an anchor have either an HREF or a NAME attribute. It need not have both.
How does this happen? Using a standard hyperlink, of course, but with a small addition. Found in the HREF attribute, the name is tacked onto the end of the URL of the document in which it appears. To do this, just enter document's URL, and then add a pound-sign and the name to the end of the URL. For example, assuming that the document's URL is
"http://www.site.edu/food.html," the pointer to the named anchor pt.3 wouldbe:
http://www.site.edu/food.html#pt.3
A hyperlink which has the above URL in its HREF attribute will take the reader straight to the text contained within the anchor <A NAME="pt.3">... </A> within the file "food.html." (Incidentally, if the browser loads a file but can't find the named anchor which has been specified, it simply goes to the top of the file, just as it would have if there hadn't been a name in the URL at all.)
Now, you may be confused about why a pound-sign (#) is in the URL. That pound-sign is how the browser knows that it's looking for a name, and how it keeps the named anchor separate from the document's filename. Therefore, if you are writing a hyperlink which points to a named anchor found within the same document, you only need to have the pound-sign followed by the name of the anchor. For example, a hyperlink to Part 3 which is found within the file "food.html" would have this markup:
<A HREF="#pt.3">Part 3</A>
A common use for named anchors is to create a "table of contents" at the top of a long document. This approach was
used in the markup of individual departments in the CWRU General Bulletin, as well as many other pages in the CWRU Web system. Each section within a document is given a named anchor, and hyperlinks to each of these anchors
are put at the top of the file.
Unlike HREF, the double-quotes in the NAME attribute are never optional (because of the # character). This has another benefit, in that you may use spaces in your name. Why does this make a difference? Here's an example, assuming for the moment that the quotes aren't used: the anchor <A NAME=section 1.2> would create an anchor name section. This is because the space between section and 1.2 would be interpreted as the separator between attributes. The Web browser would take section as the name, toss out 1.2 as an unrecognized attribute, and proceed merrily along.
Similarly, the reference <A HREF=#section 1.2> would look for an anchor named section and completely ignore the 1.2.With the use of double-quotes, which are pretty much required anyway, this problem does not occur.
I'm Still Confused...
Okay. As an example, let's say you're compiling a glossary. You decide to write a definition for "Web client" which reads, "see browser". Instead of leaving it as plain text, thereby forcing the user to scroll most of the way through the glossary to find "browser," you could set a named anchor around the term "browser" and then turn the word "browser" in the definition for "Web client" into a hyperlink to the label gl.browser-and therefore to the term "browser." Got all that? In other words, the markup used to create the entry for "Web client" would be:
<DT>Web client
<DD>see <A HREF="#gl.browser">browser</A>
Meanwhile, the markup for the "browser" entry would be:
<DT><A NAME="gl.browser">browser</A>
<DD>A program which is used to access the Web.
The user, reading through the glossary, sees the definition for "Web client." He clicks on the hyperlink in the definition (the word "browser"). This causes the browser to jump to the entry for "browser" -- no scrolling required! Go to the end of the file, where the term "Web browser" is found, and select the word "Browser." Presto!
Chapter 7: Images
Besides hyperlinks, the other great advantage of the Web is the ability to integrate graphic images into a document. Some would argue that this represents one of the greatest strengths of the Web. Graphics are certainly used as heavily as hyperlinks, and represent most of the data which is transferred, so it's fitting that we spend some time discussing them. By the time you finish this chapter, you'll be able to create eye-catching pages that will make you the envy of your friends! Okay, so that would be the case if you had friends like mine. Never mind.
IMG
Images are placed in Web documents using the IMG tag. This tag is empty, and therefore has no closing tag. The basic form of the image tag is <IMG>, but just like <A>, <IMG> by itself is pointless-- it will do nothing. At the very least, you need to let the browser know where to find the image that it's supposed to place in the document.
This brings up an important point. Visually speaking, images are part of a Web document, but in reality an HTML file and any graphics it refers to are actually all separate files. In other words, one HTML file which has five graphics within it makes a total of six files required to make the page look right. These files are all stored on a Web server, but don't have to all be in the same exact place. (Often, server administrators will set up separate directories for pictures.)
In order to make the IMG tag work, you need to use an SRC attribute. SRC stands for "source," as in, "the source of this graphic." (One way to read a typical image tag is "image source equals..." You'll see what I mean in a minute.) The value of SRC is the URL of the graphic you want to have displayed on your Web page. Thus, a typical image tag will take the form:
<IMG SRC="URL of graphic">
The URL of the graphic is just like the URLs used in the anchor tag (see previous chapter), except in this case the location used is that of the graphic file. A graphic named "blat.gif" located in the directory "pics" on the server "www.site.edu" would have the URL http://www.site.edu/pics/blat.gif. You can use either relative or full URLs to refer to the graphic file.
Okay, but how does the browser know where to put a graphic once it's been loaded? In relation to the text, the browser puts a graphic wherever an image tag occurs in the document. It will do this as though the graphic were just another piece of the text (which, in a certain way, it is). For example, if you put an image tag between two sentences, the browser would show the first sentence, then the graphic, and then the second sentence right after the graphic. Thus...
Further inquiries should be directed to Jodi at x303.
<IMG SRC="pix/redsquare.gif">
There will be a meeting next Tuesday night...
...will look like this:
Further inquiries should be sent to Jodi at x303. [Image] There
will be a meeting next Tuesday night...
Images can be placed almost anywhere within the body of the document. They can be between paragraphs, within paragraphs, in list items or definition-list definitions, and even within headings. Take a look at a few examples.
Placing images within links is also possible. To do so, merely place the IMG tag within the anchor container.
For example:
<A HREF="http://www.site.net/">
<IMG SRC="generic-image.gif">
</A>
You can also mix in text to either side of the image, or both sides: it doesn't matter. Let's say that you wanted to put a link to a copyright notice, and you wanted to draw attention to the link with a small warning symbol. It might go something like this:
<A HREF="tcopy.html">
<IMG SRC="pix/warning.gif"> Unauthorized duplication is prohibited!
</A>
The above markup would then appear as:
[Image] Unauthorized duplication is prohibited!
As you can see, if you do include text within the anchor container, then it will be a part of the anchor along with the image.
There are two other attributes to the IMG tag which should be discussed in this material. Both are less frequently used than SRC (because SRC is so essential) but each is important in its own way. In my opinion, the more important of the two is...
ALT
The ALT attribute is used to define "alternate text" for an image. The value of ALT is author-defined text, enclosed in double-quotes, and ALT text can be any amount of plain text, long or short. To pick one of an infinite number of examples, a warning symbol could be marked up as follows:
<IMG SRC="warning.gif" ALT="Warning!!!">
This ALT text will have no effect whatsoever in a graphical browser with image loading turned on. So what's the point? ALT improves the display and usefulness of your document for people who are stuck with text-only browsers such as Lynx, or who have turned image loading off. Since these users cannot see graphics, the browser will substitute a marker such as "[IMAGE]" for any image tag. This is, in effect, a placeholder, but a frustrating one, since there isn't any way for the user to tell what the image is, or what it says, or what its purpose is.
However, if ALT text has been defined, the browser will display that text instead of the placeholder. This makes the display a lot nicer and more useful for users who can't see the graphics, and doesn't affect users who can see graphics at all. A common trick to make image placeholder disappear in text-only browsers is to set the ALT text to be a single space:
<IMG SRC="generic-image.gif" ALT=" ">
Some people also use no space at all (ALT="") but this particular use of the ALT tag has been known to confuse certain Web browsers, including some older, but still common, versions of Netscape. For maximum safety, use the single-space ALT text.
Figure 1 shows two Lynx (text-based Web browser) screen-shots. The first (Figure 1a) is of a document with a number of images that have not had any ALT text defined. The second screen-shot (Figure 1b) is the same document, but this time the images have been enhanced with ALT text. Notice how the use of ALT tags significantly reduces the "clutter" in the document. If you're still somewhat confused, it may help to look at the second screen's markup.
In addition to character-based browsers, some graphical browsers will use the ALT text if automatic image-loading has been turned off. Therefore, ALT is really more of a consideration to the reader than it is a necessary component of the image tag, but it is still important to the design of any intelligently constructed Web page.
ALIGN
As was pointed out earliar, a lot of vertical space can be wasted when graphics are integrated into paragraphs. This is because ordinary HTML 2.0 does not support anything which allows for multiple lines of text flowing past a graphic.
However, the text can be shifted within the vertical space which is created by the graphic. In addition to having the text lined up with the bottom of the graphic, you can align it to either the top or the middle of the graphic. This is accomplished using the ALIGN attribute, as in the following:
<IMG SRC="generic-image.gif" ALIGN=top>
This will cause the top of any text on the same line as that graphic to be aligned with the top of the graphic. There is also an ALIGN=middle option, which will align the text's baseline with the middle of the graphic, and of course ALIGN=bottom, which is the default display strategy for most browsers. Take a look.
While the above is all true for HTML 2.0, it is also the case that the HTML 3.2 specification supports the flowing of
text around graphics (that is, allowing multiple lines to wrap around a graphic). The ability to flow text around a graphic is accomplished through an extension of the ALIGN attribute, but I will not discuss it here, leaving that instead to another material.
Getting the Right Format
Before you go flying off to create the ultimate killer graphic, you need to remember that the "universal" standard (at least for the near future) is the GIF file format. GIF stands for Graphic Interchange Format, and all graphical browsers use that format for in-lined images. While this may change to some degree in the future, for now, my advice is to use GIF files in order to ensure maximum cross-browser compatibility.
Most advanced graphics programs will save to the GIF format. If they do not, they will usually save to a format like PICT or PCX, which can then be converted using another program. If you are not sure how to get your graphics into the GIF format, ask your local computer graphics whiz.
As you have probably guessed, a discussion of graphics could fill up its own material-- there are issues like file sizing, when to use GIF and when to use JPEG, transparent areas, future development, and image mapping, just for starters.
Unfortunately, I haven't enough room in this material to tackle this subject. Besides, most of it isn't about HTML, but more about style decisions, which is outside the scope of my intent for this work.
INTERMEDIATE HTML
Tables
* Introduction to Table
* How to create a table
* Table Attributes
FORMS
Introduction to forms
* The FORM element
* Controls
* The INPUT element
* The BUTTON element
* The SELECT and OPTION elements
* The TEXTAREA element
* Labels
* The LABEL element
Chapter-1:Tables
Introduction to Table
Fortunately, HTML tables are a lot easier to create than their wooden counterpart. Tables are used extensively on many web sites to bring structure to a page. There are small tables and big tables- small ones are often used simply to encompass and organize a section of the page, such as a chart or spreadsheet-like data; large ones are used to bring organization to the entire document (as seen in the frontpage of Yahoo).
How to create a table
Begin by getting a saw and a huge piece of log...just kidding! To create a HTML table, we have to first look at the basic tags necessary to create
one:
TagFunction
<table></table>Defines a table
<tr></tr>Defines a row within the table
<td></td>Defines a cell within the table
Every single table you construct will consist of the above three tags, no matter the complexity. Shown below is the syntax of the most basic form of table, with only one row and cell:
<table>
<tr>
<td>Some text in the cell</td>
</tr>
</table>Some text in the cell
We began our journey with the <table> tag. Continuing on, we used the <tr> tag to define a row, and used one <td> tag inside to specify that this row should contain only one cell. All content, such as text (in the above example), or otherwise, go into the <td> tag, and only the <td> tag.
If you're a little confused at this stage, its ok. Practice makes perfect. Lets create a table now with one row, but two cells inside of it:
<table>
<tr>
<td>Cell #1</td>
<td>Cell #2</td>
</tr>
</table>Cell #1Cell #2
To continue on with this table madness, lets now create a table with two rows, each with two cells in them (4 cells in total). Take note of how the
<tr> and <td> tags are positioned:
<table>
<tr>
<td>Cell #1</td>
<td>Cell #2</td>
<tr>
<td>Cell #3</td>
<td>Cell #4</td>
</tr>
</table>Cell #1Cell #2
Cell #3Cell #4
Since we want two rows, there are two <tr> tags present. Since we want two cells in each of the rows, there are two <td> tags present in each <tr>.Simple as that!
Table Attributes
Tables, like many tags in HTML, accepts various attributes that control how a table is to look. Lets list some of the basic table attributes: attributesFunction
border=?Specifies the border width of the table, in pixels.
width=?Specifies the width of the table or cell, in pixels or %.
height=?Specifies the height of the. table or cell, in pixels or %
cellpadding=?Specifies the distant between the cell and the content
inside.
cellspacing=?Specifies the spacing between each cells, in pixels.
Here's an example that uses some of the above attributes:
<table border=3 width=200 cellpadding=20>
<tr>
<td>Cell #1</td>
<tr>
<td>Cell #2</td>
</tr>
</table>Cell #1
Cell #2
Tables are really quite easy to construct, once you get the hang of it.
Chapter-2 : FORMS
Introduction to forms
An HTML form is a section of a document containing normal content, markup, special elements called controls (check boxes, radio buttons, menus, etc.), and labels on those controls. Users generally "complete" forms by entering text, selecting menu items, etc., and then submitting the form for processing. Submitted forms may either be mailed to another user or fed to a program for treatment.
Each control may be assigned a name. When the form is submitted, some controls (depending on their state) have their name and current value submitted along with the form. The nature of the value submitted depends on the control (e.g., the value of a text box is the input text).
Here's a simple form that includes labels, radio buttons, and push buttons (reset the form or submit it):
<FORM action="http://somesite.com" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
Note. This specification includes more detailed information about forms in sections on form display issues.
The FORM element
<FORM> ...</FORM>
Start tag: required, End tag: required
Attribute definitions
action = url
This attribute specifies a program for handling the submitted form. Generally the URL is an HTTP URL (to submit the form to a program) or a mailto URL (to email the form).
method = get/post
This attribute specifies which HTTP method will be used to submit name/value pairs to the form handler. Possible values (which are case-insensitive):
post: Use the HTTP POST method. This method includes name/value pairs in the body of the form and not in the URL specified by the action attribute.
get:Deprecated.Use the HTTP GET method. This method appends name/value pairs to the URL specified by action and sends this new URL to the server. This is the default value for backwards compatibility. This method has been deprecated for reasons of internationalization.
style (inline style information)
title (element titles)
target (target frame information)
The FORM element acts as a container for controls. It specifies:
The layout of the form (given by the contents of the element).
The program that will handle the completed and submitted form (the action attribute). The receiving program must be able to parse name/value pairs in order to make use of them.
The method by which user data will be sent to the server (the method attribute).
A character encoding that must accepted by the server in order to handle this form (the accept-charset attribute). User agents may advise the user of the value of the accept-charset attribute and/or to restrict the user's ability to enter unrecognized characters.
A form can contain text and markup (paragraphs, lists, etc.) .
The scope of the name attribute for any controls within a FORM element is the FORM element.
The following example specifies that the submitted form will be processed by the "adduser" program. The form will be sent to the program using the HTTP POST method.
<FORM action="http://somesite.com/prog/adduser" method="post">
...form contents...
</FORM>
The following example shows how to send a submitted form to an email address.
<FORM action="mailto:Kligor.T@gee.whiz.com" method="post">
...form contents...
</FORM>
Controls
The following control elements generally appear within a FORM element declaration. However, these elements may also appear outside of a FORM element declaration when they are used to build user interfaces. This is discussed later in this specification, in the section on intrinsic events.
The INPUT element
<INPUT Type=
"(TEXT | PASSWORD | CHECKBOX |
RADIO | SUBMIT | RESET |
FILE | HIDDEN | IMAGE | BUTTON)"
>
Start tag: required, End tag: forbidden
Attribute definitions
type = text|password|checkbox|radio|submit|reset|file|hidden|image|button
This attribute specifies the type of input control to create. We discuss input control types below. The default value for this attribute is "text".
name = cdata
This attribute assigns a name to the control. This name will be paired with the current value of the control if the element's value is submitted along with the form.
value = cdata
This attribute specifies the initial value of the control. It is optional except when the control type is "radio".
size = cdata
This attribute tells the user agent the initial width of the control. The width is given in pixels, except for control types "text" and "password" when it is the (integer) number of characters.
maxlength = number
When the control type is "text" or "password", this attribute specifies the maximum number of characters that may be entered. This number may exceed the specified size, in which case the user agent should offer a scrolling mechanism. The default value for this attribute is an unlimited number.
checked
When the control type is "radio" or "checkbox", this boolean attribute specifies that the button is on. This attribute must be ignored for other control types.
src = url
When the control type is "image", this attribute specifies the location of the image to be used to decorate the graphical submit button.
Input types
The INPUT element's type attribute determines which control will be created.
text
This type creates a single-line text box. The value submitted by a text control is the input text.
password
Like "text", but the input text is rendered in such a way as to hide the characters (e.g., a series of asterisks). This control is used for sensitive input such as passwords. The value submitted by a password control is the input text (not the rendering).
Note. Application designers should note that this mechanism affords only light security protection. Although the password is masked by user agents from casual observers, it is transmitted to the server in clear text, and may be read by anyone with low-level access to the network.
checkbox
A checkbox is an on/off switch. When the switch is on, the value of the checkbox is "active". When the switch is off, the value is inactive. The checkbox value is only submitted with the form when the switch is on.
Several checkboxes within the same form may bear the same name. Upon submission, each "on" checkbox with the same name submits a name/value pair with the same name component. This allows users to select more than one value for a given property.
radio
A radio button is an on/off switch. When the switch is on, the value of the radio button is "active". When the switch is off, the value is inactive. The radio button value is only submitted with the form when the switch is on.
Several radio button within the same form may bear the same name. However, only one of these buttons may be "on" at any one time. All related buttons are set to "off" as soon as one is set to "on". Thus, for related radio buttons, only one name/value pair is ever submitted.
submit
Creates a submit button. When this button is activated by the user, the form is submitted to the location specified by the action attribute of the parent FORM element.
A form may contain more than one submit button. Only the name/value pair of the activated submit button is submitted with the form.
image
Creates a graphical submit button. The value of the src attribute specifies the URL of the image that will decorate the button. For accessibility reasons, authors should provide alternate text to the image.
When a pointing device is used to click on the image, the form is submitted and the location passed to the server.
If the server takes different actions depending on the location clicked, users of non-graphical browsers will be disadvantaged. For this reason, authors should consider alternate approaches:
Use multiple submit buttons (each with its own image) in place of a single graphical submit button. You can use style sheets to control the positioning of these buttons.
Use a client-side image map together with scripting.
reset
Creates a reset button. When this button is activated by the user, all of the form's controls have their values reset to the initial values specified by their value attributes. The name/value for a reset button are not submitted with the form.
button
Creates a push button that has no default behavior. The behavior of the button is defined by associating the button with client-side scripts that are triggered when events affecting the button occur (e.g., clicking the button). The value of the value attribute is the label used for the button.
The BUTTON element
Start tag: required, End tag: required
Attribute definitions
name = cdata
This attribute assigns a name to the button.
value = cdata
This attribute assigns a value to the button.
type = submit|button|reset
This attribute declares the type of the button. Possible values:
submit: Creates a button that submits the form that contains it. This is the default value.
button: Creates a simple push button intended to trigger a script.
reset: Creates a button that resets the form that contains it.
Attributes defined elsewhere
A BUTTON element whose type is "submit" is very similar to an INPUT element whose type is "submit". They both cause a form to be submitted, but the BUTTON element allows richer presentational possibilities. When a BUTTON whose type is "submit" is selected, the name and value are paired and submitted with the form (see the section on form submission for details).
A BUTTON element whose type is "submit" and whose content is an image (e.g., the IMG element) is very similar to an INPUT element whose type is "image". They both cause a form to be submitted, but their presentation is different. In this context, a graphical user agent may render an INPUT element as a "flat" image, and render a BUTTON as a button (e.g., with relief and an up/down motion when clicked).
The following example expands a previous example by substituting the INPUT elements that create submit and reset buttons with BUTTON instances. The buttons contain images by way of the IMG element.
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
First name: <INPUT type="text" name="firstname"><BR>
Last name: <INPUT type="text" name="lastname"><BR>
email: <INPUT type="text" name="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<BUTTON name="submit" value="submit" type="submit">
Send<IMG src="/icons/wow.gif" alt="wow"></BUTTON>
<BUTTON name="reset" type="reset">
Reset<IMG src="/icons/oops.gif" alt="oops"></BUTTON>
</P>
</FORM>
ILLEGAL EXAMPLE:
The following is not considered legal HTML.
<BUTTON>
<IMG src="foo.gif" usemap="...">
</BUTTON>
A BUTTON element whose type is "reset" is very similar to an INPUT element whose type is "reset". They both cause controls to regain their initial values, but the BUTTON element allows richer presentation.
The BUTTON element may also be used together with scripts, in which case it's type should be "button". When such a button is activated, a client-side script is executed. We discuss this use of BUTTON later in the specification in the section on intrinsic events.
The SELECT and OPTION elements
Start tag: required, End tag: required
SELECT Attribute definitions
name = cdata
This attribute assigns a name to the element. This name will be paired with any selected values when the form is submitted.
size = number
When the SELECT element is presented as a scrolling list box, this attribute specifies the number of rows in the list that should be visible at the same time. There is no requirement for visual user agents to present a SELECT element as a list box, and one alternative is to use a drop-down menu.
multiple
When set, this boolean attribute allows multiple selections. When not set, the SELECT element only permits single selections.
The SELECT element creates a group of choices that may be selected by the user. Each choice is represented by an OPTION element. A SELECT element must contain at least one OPTION element.
Zero or more choices may be pre-selected for the user. User agents should determine which choices are pre-selected as follows:
If no OPTION element has the selected attribute set, no options should be pre-selected.
If one OPTION element has the selected attribute set, it should be pre-selected.
If the SELECT element has the multiple attribute set and more than one OPTION element has the selected attribute set, they should all be pre-selected.
It is considered an error if more than one OPTION element has the selected attribute set and the SELECT element does not have the multiple attribute set.
Start tag: required, End tag: optional
OPTION Attribute definitions
The SELECT is followed by submit and reset buttons.
<FORM action="http://somesite.com/prog/component-select" method="post">
<P>
<SELECT multiple size="4" name="component-select">
<OPTION selected value="Component_1_a">Component_1</OPTION>
<OPTION selected value="Component_1_b">Component_2</OPTION>
<OPTION>Component_3</OPTION>
<OPTION>Component_4</OPTION>
<OPTION>Component_5</OPTION>
<OPTION>Component_6</OPTION>
<OPTION>Component_7</OPTION>
</SELECT>
<INPUT type="submit" value="Send"><INPUT type="reset">
</P>
</FORM>
When the form is submitted, each selected choice will be paired with the name "component-select" and submitted. The submitted value of each OPTION will be its contents, except where overridden by the value attribute (here, in the first two components).
The TextArea Element
The TEXTAREA element creates a multi-line text input control (as opposed to a single-line INPUT control). The content of this element provides the initial text presented by the control.
This example creates a TEXTAREA control that is 20 rows by 80 columns and contains two lines of text initially. The TEXTAREA is followed by submit and reset buttons.
<FORM action="http://somesite.com/prog/text-read" method="post">
<P>
<TEXTAREA name="thetext" rows="20" cols="80">
First line of initial text.
Second line of initial text.
</TEXTAREA>
<INPUT type="submit" value="Send"><INPUT type="reset">
</P>
</FORM>
Labels
Some form controls automatically have labels associated with them (press buttons created by INPUT and BUTTON) while most do not (text fields created by INPUT and TEXTAREA, checkboxes and radio buttons created by INPUT, and menus created by SELECT).
For those controls that have implicit labels, user agents should take the value of the value attribute for the label string.
To specify labels for controls without implicit labels, authors may use the LABEL element.
The LABEL element
Start tag: required, End tag: required
Attribute definitions
for = idref
This attribute explicitly associates the label being defined with another control. The value of this attribute must be the value of the id attribute of some other control in the same document. In the absence of this attribute, the label being defined is associated with its contents.
This example creates a table that is used to align two INPUT controls and their associated labels. Each label is associated explicitly with one of the INPUT elements.
<FORM action="..." method="post">
<TABLE>
<TR> <TD><LABEL for="fname">First Name</LABEL>
<TD><INPUT type="text" name="firstname" id="fname">
<TR> <TD><LABEL for="lname">Last Name</LABEL>
<TD><INPUT type="text" name="lastname" id="lname">
</TABLE>
</FORM>
This example extends a previous example form to include LABEL elements. Note that the LABEL elements are associated to the INPUT elements through the id attribute.
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM>
More than one LABEL may be associated with the same control by creating multiple references via the for attribute.
To associate a label with another control implicitly, make the control the contents of the LABEL. In this case, the LABEL may only contain one other control element. The label itself may be positioned before or after the associated control.
In this example, we implicitly associate two labels and two INPUT elements. This technique cannot be used when a table is being used for layout, with the label in one cell and its associated control in another cell.
<FORM action="..." method="post">
<P>
<LABEL>
First Name
<INPUT type="text" name="firstname">
</LABEL>
<LABEL>
<INPUT type="text" name="lastname">
Last Name
</LABEL>
</P>
</FORM>
When a LABEL element receives focus, it passes the focus on to its associated control. See the section below on access keys for examples.
Labels may be rendered by user agents in a number of ways (e.g., visually, read by speech synthesizers, etc.)
ADVANCED HTML
1.Image Map
* Working with Image Maps
* Server-Side Image Map
* Client -Side Image Map
2.Frames and Windows
* Introduction to Frame:
* Syntax
* Creating a Window
3.Cascading Style Sheet
* Introduction To StyleSheet:
* Adding style to HTML
* Setting the default style sheet language
* Inline style information
* Header style information :the STYLE element
* Inheritance and cascading
Chapter-1:Image Map
This chapter describes some of the most advanced tags of the standard HTML. You learn how to create image maps that you can use to make you Web Site easier to navigate. You also learn how to use windows and frames to display multiple Web pages at the same time.
Working With Image Maps
The home page of many sites include an image that you can click to navigate to different sections of the Web Sites. For example the image may contain an icon that represents a new section, a chat section, and a file download section. If the visitors want to go to the new section then they need to click the new icon .The image that contains this icon is called ImageMap.
A related use of image maps is for creating navigation bars on the top of every pages on a Web Site. The navigation bar contains a menu of the sites main section. Again the users can use a navigation bar to quickly and easily navigate to an area of interest for example many of the pages on the Netscape Web Site includes a navigation bar. These are the two main uses of the images maps. However there are other more imaginative ways in which they can be employed. For example one can use imagemap for gathering information. Suppose you want to know where in the world the visitors to your Web Site are coming from. You could create an image map of the world. Visitors could indicate their home country by clicking the correct area. Whenever you need to display a choice of options in a single image ,use an image map.
There are two types of image maps: Client Side and Server Side. In the ServerSide image map the Server decides which action to take when a user clicks a region of the image.In Client Side the browser decides what action to take place. Client Side image map are very first as comparable to Server Side image map.
Server Side Image Map:
If you want your image maps to work on a maximum number of browser use a server-side image map. Server-Side image maps are compatible with even the oldest browsers. The only disadvantage of server-side images map is that they are significantly slower then client-side image maps.
The Step involved are:
1.Create the Image.
2.Include the correct HTML tags in details.
3.Create a map file.
One can use any type of image file inside an image map. Generally GIF file are used but one can used JPEG,PNG etc.
While creating your image keep this in mind that the image should be so big that the user can click any part of the image by moving the mouse. Don't make your image very big but make it more artistic masterpiece, because no one will ever see it if it will take many hours to load.
The second step is to include the proper HTML tag.
<HTML>
<HEAD>
<TITLE>SERVER-SIDE IMAGE-MAP</TITLE></HEAD>
<BODY>
<A HREF="/SOMEDIRECTORY /Itmap.map"><IMG SRC="IM1.GIF" IMAGE></A>
</BODY>
</HTML>
The image that will displayed as the image map is "IM1.GIF" .
The final step to create server side image map is to create map file. A map file is a normal text file and the extension is .map. One can create its own map file by using his favourate text editor.In the previous example the image is contained inside the <A> tag.The file is itmap.map which is a map file.
Internet Information Server (the Web Server that you are using here) recognizes map files in both the NSCA and CERN formats.
Client Side Image Maps
It is used as the same purpose as that of the server-side image map. However the client side image map is very faster. But the disadvantage of the client side image map is that it does not work on the Old Browser.
<html>
<head>
<title>Client-side</title>
</head>
<Map name="mamap">
<area shape="rect" coordinates="0,0,100,100" href="/news.htm">
<area shape="rect" coordinate="101,0,200,100" href="/chat.htm">
</map>
</body>
</html>
You can use all usual attributes of the <IMG> tag. For example you should specify the WIDTH and HEIGHT attributes so the image will load faster. Also you might want to include the border=0 attributes of the <IMG> tag. If you include this attribute a border won,t appear around the outside of your image.
Chapter-2:Frames
Introduction To Frame:
The Frame are positioned so that they replace the <BODY></BODY> tag. A frame page does NOT need the <BODY></BODY> tags. eg
<HTML>
<HEAD>The Title</HEAD>
<FRAMESET>
</FRAMESET>
</HTML>
They are supported by Netscape 2+ and by Internet Explorer 3+.
Syntax
* <FRAMESET> - This is what goes in place of the <BODY> tags, It tells the browser that you are using frames. Also in this tag goes all the options to do with how many Columns or Rows are used and how thick the border between frames is (if there is one at all). The optional commands used in this tag to set attributes such as frame colour, borders, margins apply to all the frames in the <FRAMESET>. It sets the options globally for the other frames put they can be over-ruled by individual options in the <FRAME> tag.
* COLS - Divides the page into columns. eg
<FRAMESET COLS="20%,80%">
divides the screen up into two columns, the left hand one taking up 20% of the space and the right hand one taking up 80% of the space.
* ROWS - Divides the screen up into rows eg
<FRAMESET ROWS="10%,85%,5%">
divides the screen into 3 rows, 10% at the top, 85% in the middle and 5% at the bottom. For both rows and columns as well as using the % space of the screen you can also define how many pixels each part is to use.
<FRAMESET ROWS="150,*">
divides the screen into two rows, the top one being 150 pixels tall and the bottom one taking up the rest of the space. The "*" tells it to fit this row into what ever space is left.
* BORDER - (Netscape only) allows you to set the width of all the borders in pixels.
<FRAMESET ROWS="150,*" BORDER="1">
* FRAMEBORDER - (Internet Explorer Only) lets you say whether there is to be a border or not. The value is either yes or no. The value applies to all the frames.
* BORDERCOLOR - (Netscape Only) allows you to set the colour of all the borders using the normal #rrggbb HEX values. It can also be used in the <FRAME> tag to set the colour of individual frame borders.
* <FRAME> - This is the tag that is used to name the URL's of the pages that are going in the frames that you set out with the <FRAMESET> tag. The optional commands used in this tag to set attributes such as frame colour, borders, margins apply only to the frame that you put them in. These options will over-rule any global options that you put in the <FRAMESET> tag. You can use as many of these optional tags in each <FRAME> tag as you want. The order that you put them in is not important.
* SRC - give the URL of the page that is to go into the frame.
* NAME - gives the frame a name so that when someone clicks on a link the page will load into the correct frame.
<FRAMESET ROWS="150,*">
<FRAME SRC="menu.htm" NAME="menu_frame">
<FRAME SRC="main.htm" NAME="main_page">
</FRAMESET>
This sets out a page with 2 frames as before "menu.htm" goes in the top frame and "main.htm" goes in the bottom one. The page will be set out like the picture below.
************************
* menu.htm *
* *
************************
* *
* *
* main.htm *
* *
* *
************************
It is important to name the frames so that then when someone clicks on a link you can direct it into the correct frame. The following link can be placed in the top frame (menu.htm) and when clicked it will load into the bottom frame (main.htm which we have named "main_page".)
<A HREF="page2.html" TARGET="main_page">
This loads the page into the main frame.</A>
would load the page "page2.html" into the frame called "main_page" which in this example is the bottom frame.
*************************
* m * *
* e * *
* n * main.htm *
* u * *
* . * *
* h * *
* t * *
* m * *
* * *
*************************
<HTML>
<HEAD>
<TITLE>A Left Hand Menu</TITLE>
<FRAMESET COLS="15%,*">
<FRAME SRC="menu.htm" NAME="menu_frame">
<FRAME SRC="main.htm" NAME="main_page">
</FRAMESET>
<NOFRAMES>This page uses Frames</NOFRAMES>
</HTML>
To make more complicated frame layouts you may have to use more than one <frameset> tag. Don't forget that however many <FRAMESET> 's you use you need that number of </FRAMESET> 's at the end.
*************************
* menu.htm *
* *
*************************
* s * *
* i * *
* d * main.htm *
* e * *
* . * *
* h * *
* t * *
* m * *
* * *
*************************
<HTML>
<HEAD>
<TITLE>3 Frames</TITLE>
<FRAMESET ROWS="15%,*">
<FRAME SRC="menu.htm" NAME="menu_frame">
<FRAMESET COLS="15%,*">
<FRAME SRC="side.htm" NAME="side">
<FRAME SRC="main.htm" NAME="main_page">
</FRAMESET>
</FRAMESET>
<NOFRAMES>This page uses Frames</NOFRAMES>
</HTML>
*************************
* * menu.htm *
* * *
* *********************
* s * *
* i * *
* d * main.htm *
* e * *
* . * *
* h * *
* t * *
* m * *
* * *
*************************
<HTML>
<HEAD>
<TITLE>3 Frames</TITLE>
<FRAMESET COLS="15%,*">
<FRAME SRC="side.htm" NAME="side">
<FRAMESET ROWS="15%,*">
<FRAME SRC="menu.htm" NAME="menu_frame">
<FRAME SRC="main.htm" NAME="main_page">
</FRAMESET>
</FRAMESET>
<NOFRAMES>This page uses Frames</NOFRAMES>
</HTML>
* SCROLLING - This sets whether the frame will have scroll bars. The options are yes, no & auto. The auto put scroll bars on if they are needed and leaves them out if they are not.
<FRAME SRC="top.htm" NAME="menu_frame"
SCROLLING=no>
forces the browser to leave out the scroll bars for the top.htm page.
* NORESIZE - This stops the frame from being resized by the user.
<FRAME SRC="top.htm" NAME="menu_frame"
NORESIZE>
* FRAMEBORDER - (Internet Explorer Only) lets you say whether there is to be a border or not in the specific frame that you put the tag. The value is either yes or no.
<FRAME SRC="top.htm" NAME="menu_frame"
FRAMEBORDER=no>
* MARGINWIDTH - Lets you set the left and right margin widths of the frame in pixels.
<FRAME SRC="top.htm" NAME="menu_frame"
FRAMEBORDER=no MARGINWIDTH="5">
* MARGINHEIGHT - Lets you set the top and bottom margin heights of the frame in pixels.
* FRAMESPACING - (Internet Explorer Only) lets you set space around the frame.
* BORDERCOLOR - (Netscape Only) allows you to set the colour of the border using the normal #rrggbb HEX values. It can also be used in the <FRAME> tag to set the colour of individual frame borders.
* NOFRAMES - The contents of this are displayed if the persons browser does not support frames. It is placed after the </FRAMESET> tag.
<NOFRAMES>This page uses Frames</NOFRAMES>
Creating a Window
Frames are contained in a browser windows.Generally all HTML are displayed in a browser window.One can also create additional windows.And can also display different pages at the same time .
The procedure of creating a new browser window is pretty simple .Just go tyhrough this example
<HTML>
<HEAD>
<TITLE>Windows<TITLE> <HEAD>
<BODY>
<A href="apage.html" onewindow">Click Me!</A>
</BODY></HTML>
When this file displayed in the browser the hypertext Link "Click Me!" will displayed .Once you click this link then another window will be displayed on the screen.In the new window the HTML file apage.html is loaded.
Note:You will learn more about Window when you wil go to JavaScript.
Chapter-3:Cascading Style Sheet
Introduction to style sheets
Style sheets represent a major breakthrough for Web page designers, expanding their ability to improve the appearance of their pages. In the scientific environments in which the Web was conceived, people are more concerned with the content of their documents than the presentation. As people from wider walks of life discovered the Web, the limitations of HTML became a source of continuing frustration and authors were forced to sidestep HTML's stylistic limitations. While the intentions have been good -- to improve the presentation of Web pages -- the techniques for doing so have had unfortunate side effects. These techniques work for some of the people, some of the time, but not for all of the people, all of the time. They include:
* Using proprietary HTML extensions
* Converting text into images
* Using images for white space control
* Use of tables for page layout
* Writing a program instead of using HTML
These techniques considerably increase the complexity of Web pages, offer limited flexibility, suffer from interoperability problems, and create hardships for people with disabilities.
Style sheets solve these problems at the same time they supersede the limited range of presentation mechanisms in HTML. Style sheets make it easy to specify the amount of white space between text lines, the amount lines are indented, the colors used for the text and the backgrounds, the font size and style, and a host of other details.
For example, the following short CSS style sheet (stored in the file "special.css"), sets the text color of a paragraph to green and surrounds it with a solid red border:
P.special {
color : green;
border: solid red;
}
You may link this style sheet to the source HTML document with the link element:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<LINK href="special.css" rel="stylesheet" type="text/css">
</HEAD>
<BODY>
<P class="special">This paragraph should have special green text.
</BODY>
</HTML>
HTML 4.0 provides support for the following style sheet features:
Flexible placement of style information
Placing style sheets in separate files makes them easy to reuse. Sometimes it's useful to include rendering instructions within the document to which they apply, either grouped at the start of the document, or in attributes of the elements throughout the body of the document. To make it easier to manage style on a site basis, this specification describes how to use HTTP headers to set the style sheets to be applied to a document.
Independence from specific style sheet languages
This specification doesn't tie HTML to any particular style sheet language. This allows for a range of such languages to be used, for instance simple ones for the majority of users and much more complex ones for the minority of users with highly specialized needs. The examples included below all use the CSS (Cascading Style Sheets) language but other style sheet languages would be possible.
Cascading
This is the capability provided by some style sheet languages such as CSS to allow style information from several sources to be blended together. These could be, for instance, corporate style guidelines, styles common to a group of documents, and styles specific to a single document. By storing these separately, style sheets can be reused, simplifying authoring and making more effective use of network caching. The cascade defines an ordered sequence of style sheets where rules in later sheets have greater precedence than earlier ones. Not all style sheet languages support cascading.
Media dependencies
HTML allows authors to specify documents in a media-independent way. This allows users to access Web pages using a wide variety of devices and media, e.g., graphical displays for computers running Windows, Macintosh OS etc , devices for television sets, specially adapted phones and PDA-based portable devices, speech-based browsers, and braille-based tactile devices.
Style sheets, by contrast, apply to specific media or media groups. A style sheet intended for screen use may be applicable when printing, but is of little use for speech-based browsers. This specification allows you to define the broad categories of media a given style sheet is applicable to. This allows user agents to avoid retrieving inappropriate style sheets. Style sheet languages may include features for describing media dependencies within the same style sheet.
Alternate styles
Authors may wish to offer readers several ways to view a document. For instance, a style sheet for rendering compact documents with small fonts, or one that specifies larger fonts for increased legibility. This specification allows authors to specify alternate style sheets and to declare a default style sheet. User agents should give users the opportunity to select from among alternate style sheets or to switch off style sheets altogether.
Performance concerns
Some people have voiced concerns over performance issues for style sheets. For instance, retrieving an external style sheet may delay the full presentation for the user. A similar situation arises if the document head includes a lengthy set of style rules.
The current proposal addresses these issues by allowing authors to include rendering instructions within each HTML element. The rendering information is then always available by the time the user agent wants to render each element.
In many cases, authors will take advantage of a common style sheet for a group of documents. In this case, distributing style rules throughout the document will actually lead to worse performance than using a linked style sheet, since for most documents, the style sheet will already be present in the local cache. The public availability of good style sheets will encourage this effect.
Adding style to HTML
Note. The sample default style sheet for HTML 4.0 that is included in expresses generally accepted default style information for each element. Authors and implementors alike might find this a useful resource.
HTML documents may contain style sheet rules directly in them or they may import style sheets. Any style sheet language may be used with HTML. A simple style sheet language may suffice for the needs of most users, but other languages may be more suited to highly specialized needs. This specification uses the style language "Cascading Style Sheets", abbreviated CSS, for examples.
Setting the default style sheet language:
The syntax of style data is that of the style sheet language, not HTML. Since user agents that support style sheets must parse these rules, authors must specify which style sheet languages are being employed.
Authors should use the meta element to set the default style sheet language for a document. For example, to set the default to CSS, authors should put the following declaration in the head of their documents:
<META http-equiv="Content-Style-Type" content="text/css">
The default style sheet language may also be set with HTTP headers. The above meta declaration is equivalent to the HTTP header:
Content-Style-Type: text/css
User agents should determine the default style sheet language for a document according to the following steps (highest to lowest priority):
1. If any meta declarations specify the "Content-Style-Type", the last one in the character stream determines the default style sheet language.
2. Otherwise, if any HTTP headers specify the "Content-Style-Type", the last one in the character stream determines the default style sheet language.
3. Otherwise, the default style sheet language is "text/css".
Documents that include elements that set the style attribute but which don't define a default style sheet language are incorrect. Authoring tools should generate default style sheet language information (typically a meta declaration) so that user agents do not have to rely on a default of "text/css".
Conforming HTML parsers must be able to distinguish HTML from style sheet rules. The style element and the style attribute define the beginning of style sheet data. The end of style sheet data is defined as the SGML end tag open delimiter (</). All style sheet data must be provided to the user agent's appropriate style sheet handler. Style sheets apply to the contents of HTML elements, which begin immediately after a start tag close delimiter (>). The end of this style sheet data is defined as the end tag open delimiter
style = cdata
This attribute specifies style information for the current element.
The style attribute specifies style information for a single element. The style information is specified using the default style sheet language.
This example sets color and font size information for the text in a specific paragraph.
<P style="font-size: 12pt; color: fuchsia">Aren't style sheets wonderful?
Note the syntax of a CSS declaration: name : value. Property declarations are separated by a semi-colon.
The style attribute may be used to apply a particular style to an individual HTML element. If the style will be reused for several elements, authors should use the STYLE element to regroup that information. For optimal flexibility, authors should define styles in external style sheets.
Header style information: the STYLE element
Start tag: required, End tag: required
Attribute definitions
type = content-type
This attribute specifies the style sheet language of the element's contents and overrides the default style sheet language. The style sheet language is specified as a content type (e.g., "text/css"). Authors must supply a value for this attribute; there is no default value for this attribute.
The following CSS style declaration puts a border around every H1 element in the document and centers it on the page.
<HEAD>
<STYLE type="text/css">
H1 {border-width: 1; border: solid; text-align: center}
</STYLE>
</HEAD>
To specify that this style information should only apply to H1 elements of a specific class, we modify it as follows:
<HEAD>
<STYLE type="text/css">
H1.myclass {border-width: 1; border: solid; text-align: center}
</STYLE>
</HEAD>
<BODY>
<H1 class="myclass"> This H1 is affected by our style </H1>
<H1> This one is not affected by our style </H1>
</BODY>
Finally, to limit the scope of the style information to a single instance of H1, set the id attribute:
<HEAD>
<STYLE type="text/css">
#myid {border-width: 1; border: solid; text-align: center}
</STYLE>
</HEAD>
<BODY>
<H1 class="myclass"> This H1 is not affected </H1>
<H1 id="myid"> This H1 is affected by style </H1>
<H1> This H1 is not affected </H1>
</BODY>
Although style information may be set for almost every HTML element, two elements, DIV and SPAN, are particularly useful in that they do not impose any presentation semantics (besides block-level vs. inline). When combined with style sheets, these elements allow users to extend HTML indefinitely, particularly when used with the class and id attributes.
In the following example, we use the SPAN element to set the font style of the first few words of a paragraph to small caps.
<HEAD>
<STYLE type="text/css">
SPAN.sc-ex { font-variant: small-caps }
</STYLE>
</HEAD>
<BODY>
<P><SPAN class="sc-ex">The first</SPAN> few words of
this paragraph are in small-caps.
</BODY>
In the following example, we use DIV and the class attribute to set the text justification for a series of paragraphs that make up the abstract section of a scientific article. This style information could be reused for other abstract sections by setting the class attribute elsewhere in the document.
<HEAD>
<STYLE type="text/css">
DIV.Abstract { text-align: justify }
</STYLE>
</HEAD>
<BODY>
<DIV class="Abstract">
<P>The Chieftain product range is our market winner for
the coming year. This report sets out how to position
Chieftain against competing products.
<P>Chieftain replaces the Commander range, which will
remain on the price list until further notice.
</DIV>
</BODY>
Inheritance and cascading
When the user agent wants to render a document, it needs to find values for style properties, e.g. the font family, font style, size, line height, text color and so on. The exact mechanism depends on the style sheet language, but the following description is generally applicable:
The cascading mechanism is used when a number of style rules all apply directly to an element. The mechanism allows the user agent to sort the rules by specificity, to determine which rule to apply. If no rule can be found, the next step depends on whether the style property can be inherited or not. Not all properties can be inherited. For these properties the style sheet language provides default values for use when there are no explicit rules for a particular element.
If the property can be inherited, the user agent examines the immediately enclosing element to see if a rule applies to that. This process continues until an applicable rule is found. This mechanism allows style sheets to be specified compactly. For instance, authors may specify the font family for all elements within the body by a single rule that applies to the body element.
Hiding the content of style elements from non-conforming user agents
Some style sheet languages support syntax intended to allow authors to hide the content of style elements from non-conforming user agents.
This example illustrates for CSS how to comment out the content of style elements to ensure that older non-conforming user agents will not render them as text.
<STYLE type="text/css">
<!--
H1 { color: red }
P { color: blue}
--></STYLE>
LEARNING JAVASCRIPT : PART I
What is Javascript ?
HTML allows web designers to create structured, laid out pages with images, text, and the like. HTML is good for static web pages and for comprehensible defining of static pages in an appealing manner. But merely designing static web pages is just not enough because as the web grows it needs an interactivity and instant feedback. For this, HTML is not any more enough. The designer requires something more. And this something makes them to go for a scripting language known as JavaScript.
JavaScript originated at Nescape Communications Corp. in the Year 1995. Originally they named it as LivaScript and later for marketing purposes they renamed it as JavaScript. JavaScript was built directly on the browser and is embedded inside the HTML tag. Besides JavaScript there are other scripting languages known as Perl,VBScript,PHP3.0 etc.
JavaScript Vs CGI
Perhaps it's easiest to start by explaining what JavaScript isn't. It is not a new kind of CGI (Common Gateway Interface), the traditional way of processing fill-in forms on the Web. With CGI, interactivity involves the Web server, since the user input from the form is sent back to the server, where it is processed, and then some kind of response is returned to the user. JavaScript (among other things) also can process forms, but it does so locally, on the user's machine, without contacting the server. The Web server's role with JavaScript is limited to serving the Web page containing JavaScript to the user. Since server access is not required, the HTML files containing JavaScript could just as easily be called up locally from the hard drive or a floppy disk. This makes the use of JavaScript more flexible than CGI, since it can be used on computers which are not even connected to the Internet.
JavaScript Vs Java
JavaScript is not the same as Java. Java is a full-fledged programming language allowing for creation of "applets" or mini-programs which can be run inside of Web browsers such as Netscape Navigator, Internet Explorer. Although applets appear to be integrated into the Web page displayed, they are actually independent programs and in fact Java can be used to create programs divorced from Web pages. Java applets are not part of the HTML which displays the page, although some parameters of Java applets may be set through the use of HTML. Java must be compiled (translated into byte code) before running.
JavaScript on the other hand functions as an add-on to HTML and appears as text alongside familiar HTML codes; JavaScript code is interpreted and run by the Web browser when a user retrieves the Web page, it does not need to be compiled into a program. The fact that Java applets are compiled means that if you want to take a peek at the code to see how that clever person created that special effect -- you're out of luck. The only way you can see the underlying code is if the programmer decides to make it available to you in text form. Since JavaScript is text and is included alongside regular HTML, you can see its code. Simply "view document source" on your Web browser and you'll see not only the HTML but the JavaScript as well. This makes it much easier to learn, since you can see and borrow code in just the same way you can with HTML. Probably the best way to get started is to take some existing JavaScript code and to paste it into one of your own Web pages. After you get it to work with your page, you can go in and customize the code to fit your needs. . Be forewarned -- as you'll see in the other part of this materials, JavaScript is computer code and despite Netscape's contention that it derives from (reasonably comprehensible) scripting languages such as Hypertalk (HyperCard's language), it definitely is greektalk and any similarity it has to English is just a passing coincidence. I might mention that if you do take the plunge and learn JavaScript, you'll be half way home to learning Java. The syntax is virtually identical, Java simply adds much more to the language which increases dramatically its functionality.
The JavaScript language resembles Java, but without Java's static typing and strong type checking. JavaScript supports most of Java's expression syntax and basic control flow constructs. In contrast to Java's compile-time system of classes built by declarations, JavaScript supports a run-time system based on a small number of data types representing numeric, boolean, and string values. JavaScript has a simple instance-based object model that still provides significant capabilities.
JavaScript also supports functions, again without any special declarative requirements. Functions can be properties of objects, executing as loosely typed methods.
JavaScript complements Java by exposing useful properties of Java applets to script authors. JavaScript statements can get and set exposed properties to query the state or alter the performance of an applet or plug-in.
Java is an extension language designed, in particular, for fast execution and type safety. Type safety is reflected by being unable to cast a Java int into an object reference or to get at private memory by corrupting Java bytecodes.
Java programs consist exclusively of classes and their methods. Java's requirements for declaring classes, writing methods, and ensuring type safety make programming more complex than JavaScript authoring. Java's inheritance and strong typing also tend to require tightly coupled object hierarchies.
In contrast, JavaScript descends in spirit from a line of smaller, dynamically typed languages like HyperTalk and dbase. These scripting languages offer programming tools to a much wider audience because of their easier syntax, specialized built-in functionality, and minimal requirements for object creation.
The following table compares and contrasts JavaScript and Java.
JavaScript Java
Interpreted (not compiled) by client. Compiled on server before execution on client.
Object-based. Code uses built-in, Object-oriented. Applets consist of
extensible objects, but no classes object classes with inheritance.
inheritance.
Code integrated with, and embedded Applets distinct from HTML
in HTML. (accessed from HTML)
Variable data types not declared Variable data types must be
(loose typing). declared
(strong typing).
Dynamic binding. Object references Static binding. Object references
checked at run-time. Must exist at compile-time.
Cannot automatically write to hard Cannot automatically write to
disk. hard disk.
Javascript Basics through Examples :
If you've been surfing the Web much, you will have encountered sites using JavaScript, most commonly in the form of a running message in the status bar at the bottom of the browser window or through an "alert" window that pop ups when you first access the page. There are any number of cute but ultimately annoying "features" you can add to Web pages using JavaScript. We have to accept the interactive functionality that JavaScript and other innovations bring at the cost of having to endure rapid rolling messages or frantically repeating animations. The frequency with which we encounter the running message in the status bar, by the way, is an indication of how easy it is to copy and paste JavaScript into your pages, since that code is quite complex, whereas finding the string to change inside that code from "Welcome to Intenet Explorer" to "Welcome to Home page of ACP " is no sweat.
Why JavaScript is Easy:
Basically the syntax of the JavaScript are almost similar as that of C,C++,Java. Hence those who are having the knowledge of these programming language can easily write program on JavaScript. And those who donot have programming knowledge also can write JavaScript because this is the first step for writing complex program.
Why JavaScript is Important for Web Development:
The purpose of JavaScript is to make user more interactive and feedback, multimedia and animation and to link to HTML to other technologies such as Java, ActiveX etc.
Event Handlers: JavaScript can catch event that occurred on a page, such as clicking of a form button ,or the mouse move over a link, or on Clicking an Image .JavaScript event handler can then execute code depending on these event.
Document Object Model: The HTML defined objects such as button, form,
layer of contents can be controlled by JavaScript The document object model tells how JavaScript control Objects? And which object to control by JavaScript? .With the progress of Dynamic HTML page the DOM has controlled over all the objects defiened on a page and this enable the Web Developer to design powerful Multimedia Animation using JavaScript.
What is the Disadvantage of JavaScript:
Although JavaScript has came into market in the year 1995.Since then a lot of change has made in the original Script. Hence the new change that has been made wont be supported by old browser. Thus it wont run in the old browser. Microsoft had to reverse-engineer the implementation of JavaScript into JScript because there was no original JavaScript standard to follow. Due to this some script wont be supported by IE(InternetExplorer).Hence those wont run in the IE browser.
Write Your First JavaScript:
<Script >
alert("WelCome to the World of JavaScript");
</Script>
How To Write Your FirstScript
1.Write this script on a text editor (i.e NotePad.WordPad etc).
2.Save this file with an extension of .html or .htm
3.Open your favorite browser.
4.Open the file saved on the Address box of the browser.
The result of the example is:
The browser will open an alert box and on which "Welcome to the World of JavaScript" is displayed.
Here we have defined the script tag which is a HTML tag so the browser will check for this tag and when it will found this tag then it will perform the operation that is being mentioned in side the script.
We can also write the script inside the HTML tag:
<html>
<head>
<title>This is My First JavaScript</title>
</head>
<body>
<script>
document.write("<p>The Course is Designed By ACP</p>")
alert("WelCome to the World of JavaScript");
</script>
</body>
</html>
The other way of writing JavaScript is to defined the Language as JavaScript. For example
<script Language="JavaScript">
document.write("<b> Say Hello To Your Friend</b>");
</script>
Now the question arises even though the script can result by writing <script> tag why should one go for the< script Language="JavaScript"> tag. Because JavaScript is not the only Web scripting language used. The other scripting language used is VBScript. But VBScript only supported by Internet Explorer. Hence we have to defined the second tag. But by default the browser always take the script as JavaScript only. Hence even though you will not mentioned regarding the language used the browser will take it is as JavaScript only.
For displaying the data on a web Page we have to defined it inside a method called write().Document is an Object. The Script will always ended up with a closed tag known as </script>.The content inside the Script tag is nothing but pure JavaScript. The SCRIPT tag can be defined any where inside the HTML document. Either inside the head or inside the body part. Generally
the script which is being placed inside the head will be executed first and then the body part will be executed. Inorder to call a function inside the page manytimes it's better to define the function inside the head part of the HTML document.
1) Displaying alert boxes
Speaking of annoying gadgets, let's look first at how to create a pop-up alert window. Actually, this function can be useful. Say you want to inform your students of an important change in the class schedule -- you could make your point very clearly with such a Pop-up-alert. Clicking on the link in the previous sentence produces the alert message (assuming you're using a Web browser with JavaScript capability) but that could also happen automatically when the page is loaded. We're look at that option first. There are actually two snippets of JavaScript that causes this alert to pop up when the page is loaded. This is how the HTML at the top of the page looks:
<html>
<head><title>First JavaScript</title>
<! -- Hide JavaScript from non-compatible browsers>
<script language = "JavaScript">
function showAlert () {
alert ('Welcome to JavaScript!')
}
</script>
<!-- end hiding -->
You will normally define in this way between <script> tags the JavaScript "functions" (or sub-routines) which you want to have available to the user at the opening of your HTML file. Note that if you don't want users without a JavaScript-capable browser to see the JavaScript code on their screen, you can use the commenting tags in HTML "<! -->" to hide the code. The "function showAlert()" line begins the definition of the function I've named "showAlert." This is a function I am defining so I could have given it any name such as "PeanutsAndBeer", but it helps to use a name that has some relationship to what the function does. Capitalization is up to you, but JavaScript is case sensitive so you'll need to write the name of the function exactly the same way later on. The line "alert ('Welcome to JavaScript!')" defines between curly brackets the action we want to have take place when the function "showAlert()" is evoked later. In this case we're using a predefined function called "alert()" which displays an alert window. Now all we have to do is to activate the "showAlert()" function, in this case by telling the browser to run the function when the page is loaded. We do that with the following JavaScript at the end of the HTML file:
</head>
<script>
onLoad = showAlert()
</script>
</body>
</html>
Once again "onLoad" is predefined and tells the browser that whatever follows the equal sign should be done when the user loads the page, in this case run the "showAlert()" function. We called our "showAlert()" function from an "onLoad" script, but that function (and any other) can be evoked in a number of ways. We could, for example, create a hypertext link which would also result in the alert window being displayed:
<A HREF = "javascript: showAlert()">Pop up alert window</a>
This is the familiar syntax for defining a hypertext link, but in this case "http://" is replaced with "javascript:". Another possibility is to create a button to perform that action:
In this case, the code to create the button must be placed within "form" tags since a button is a form element (as are text entry fields, radio buttons and checkboxes) and won't be displayed unless within a defined form. The code for doing that looks like this:
<form>
<INPUT TYPE = button VALUE = 'Pop up alert' onClick = alert ('Hello world!')>
</form>
In addition to the alert window, there are several other dialog boxes which can be accessed through Javascript, which can ask the user to make a choice or to write in some text.
2) Putting text in status bar
I mentioned earlier using JavaScript to place a message in the status bar. Here's an example of causing a message to appear when the user puts the mouse cursor over a specific hypertext link. The JavaScript for this is put into the hypertext link:
<A HREF = "anylink.html" onMouseOver = "window.status = 'Here I am, down here!';return true">Pass mouse over me</a>
Once again, "onMouseOver" is pre-defined in JavaScript. One use of this function is to create a glossary, which is activated by the cursor moving over a phrase.
An Example of displaying Date and Time :
<html>
<head><title>EXAMPLE</title></head>
</body>
<script Language="JavaScript">
var now=new Date();
var hour=now.getHours();
document.write(hour);
if (hour>10 && hour<=12)
{
document.bgColor="Green";
document.fgColor="Red";
document.write("<B> I Am Wishing You a very Good Morning </B>");
}
else {
document.bgColor="Red";
document.fgColor="Green";
document.write("<I>I am wishing You a Good AfterNoon<I>");
}
</script>
</body>
</html>
Description Of the Example:
The line var now=new Date(); simply create an object known as Date() and gives it the name now.From this point the current Date and Timewill represent to now.The second script var hour=now.getHours();says to get the value of the current Date and to place them on the variable hour.Now hour will have the value of current Hour.The third Script display the value of the current hour on the browser.
The if statement
If(this is the case)
{
then run this code
}
else
{
run this code
}
document.bgColor="Green"
It will set the background color as Green. There are two ways of representing the Color. One way is as represented above and the other way is the hexadecimal representation
i.e
#000000 for black
#ffffff for white
#ff0000 for red
#00ff00 for green
#0000ff for blue
etc.
Note: While getting the system date and time always keep in mind that the result will be numbers and not in words.
How to get Time using JavaScript
Year year=now.getYear() It will return the current Year
Month mont=now.getMonth() It will return the curr month
Day day=now.getDay() It will get the current day
Hours hour=now.getHours() It will get the current Hour
Minutes min=now.getMinutes() It will get the current Minutes
Seconds sec=new.getSeconds() It will get the current Seconds
Example :
<script>
var now = new Date();
var day = now.getDay();
var dayname;
if (day == 0) dayname = "Sunday";
if (day == 1) dayname = "Monday";
if (day == 2) dayname = "Tuesday";
if (day == 3) dayname = "Wednesday";
if (day == 4) dayname = "Thursday";
if (day == 5) dayname = "Friday";
if (day == 6) dayname = "Saturday";
document.write("Today is " + dayname);
</script>
Hiding JavaScript from old browsers
<SCRIPT>
<!-HIDE IT FROM OTHER BROWSER
JavaScript source code
// STOP HIDING ME
</SCRIPT>
Every thing between the HTML comments will be ignored by the old browsers. This type of comments are generally written at the beginning or at the end of the script. It is important to put the comments at the respective lines. If you put them in the same line as that of the code then the code will be hidden and the browser will not display anything. JavaScript will show an error.
3) Opening and writing to windows
One of the most useful functions in JavaScript is the ability to open new windows and write to them. We are using here a "JavaScript:" link to call the function "openWindow()" which we had defined in the header:
function openWindow () {
window.open("hello.html","hello","width=240,height=200");
}
Note that we can specify the size of the new window, as well as other features, such as whether it displays the tool bar, is scrollable, etc.
A single page on a website is considered as a window. One can control the location of the window, their size, as well as create new window on the same window. And the interesting thing is that the window can talk with each other. Lets go for some classic example of a window
<SCRIPT>
<!-
window.location="http://www.hotmail.com"
//-->
</SCRIPT>
The above example will display the hotmail's home page.
<FORM>
<INPUTTYPE=BUTTON VALUE="H" onClick="window.location='h1.html';">
</FORM>
This example will open the "h1.html" page as a separate window as soon as the button will be clicked.
Inplace of onClick you can used onMouseOver(Built JavaScript).So that as soon as the mouse will be on the button the reference page will be displayed immediately.
Example:
<html>
<head>
<title>Designing with JavaScript CD Code</title>
<script>
<!-- hide it
function open_window(url)
{
email=window.open(url,"eMail",'toolbar=0,location=0,
directories=0,status=0,menubar=0,scrollbars=0,resizable=0,
width=520,height=350');
}
// -->
</script>
</head>
<body>
<h1>Second Opinion</h1>
<a href="javascript:open_window('ns1.htm')">Rafe Needleman says...</a><P>
<a href="javascript:open_window('ns2.htm')">Rex Baldazo
says...</a>
</body>
</html>
4) Manipulating values in form fields
Another very useful JavaScript feature is its ability to manipulate data in forms. The next example shows that you can create customized buttons as well as write to fields in a form.
Clicking on the first button puts the string "Hello world!" into the field. Clicking the second button selects that field. The code:
<input type=text name=field1>
<input type=button value="Put in value" onClick="document.forms[3].field1.value='Hello world!'">
<input type=button value="Select value" onClick="document.forms[3].field1.focus();document.forms[3].field1.select()">
Note that the first "input" tag defines the fill-in form and names it "field1", defining it as a "text field." The reference in the buttons through "document.forms[3].field1.value" is in the normal dot syntax to this field. This functionality is used in the quiz example described in the next section. Since JavaScript can access the contents of a field, it can also determine if what the user typed into the form is a correct response. Code:
function checkValue () {
var answer = document.forms[3].field1.value;
if (answer == "Hello world!") {
alert ("Right answer");
}
else {
alert ("Wrong answer")
}
}
The function "checkValue()" first defines a variable ('var") "answer" to be whatever the user has entered into field1. It then matches that answer against the value "Hello world!", which is in this case the response we want. A right or wrong answer triggers an alert window.
Objects:
There are billons of object in the real world for ex tree,computer,harddisk, telephone etc.,almost every thing we are dealing with in our day today life are known as object. It is not wrong if we say that we are staying in a object oriented world. The necessity of objects are so in the life of a being that they try to use the object oriented language c++, java etc in a wide range. JavaScript is also partly supporting object oriented programming. Already we have discussed objects like Date(),document etc. programming but lack of many principles of a real object oriented JavaScript can do thing not only to the Objects but also to their properties. Properties are the status of the object .For example the window object have the properties called open.
An example to know how really the objects work
var mycar=new Car();
Here mycar is the object created, and the car object has many properties such as color, brand, price etc. and this can be defined as mycar.color="red";The object mycar is different from its properties color by a dot mark. Another example is window.location=http://www.hotmail.com;
This following code for example takes the window to a document located at http://www.hotmail.com
To add more livelyness to the JavaScript we need to add methods and function to the properties.Methods like function are act upon JavaScript.
Consider the example of the car again with its property we can add an action to the car such as break, accelerator etc. For example mycar. acclerator(15).
Javascript, "Dynamic HTML" and Style Sheets
JavaScript is a key ingredient in the implementation by Netscape of what is being called "Dynamic HTML" or DHTML. DHTML aims to make virtually everything on the Web page accessible to change in reaction to user actions. This includes the possibility of knowing where on the page a user has clicked. By making everything on a Web page both "hot" and changeable, a dynamic environment is being created with functionality similar to what is possible with traditional multimedia authoring systems.
The major addition to the HTML language which enables dynamic access to page elements are Cascading Style Sheets, a standard endorsed by the W3 Consortium as "CSS1". Style sheets allow Web authors to control globally--even across an entire Web site -- the appearance of elements on a Web page. This creates a "dynamic objet model" (DOM) allowing user or programmatic access to page elements. In a style sheet definition, a page element such as a header might be initially defined to display as bold and green, but through a user action or a scripted function could be changed to italics and blue. This kind of interactivity is all local, not requiring any communication with the Web server, once the page has been displayed. The full power of DHTML will be evident when style sheets are tied directly to a common scripting language, something both Netscape and Microsoft have pledged to support (ECMAScript).
SIDE TRAIL: (Cookies and JavaScript)
If you look at the code for any JavaScript above, you can see that the answers are right there, embedded in the JavaScript. How can you avoid that? One way is to send the answers encoded as "cookies" . Cookies are another Netscape innovation, now supported by most browsers. Cookies in this sense are nothing you can sink your teeth into, but are text strings that are saved temporarily on your computer. Cookies can be manipulated either with CGI scripts or with JavaScript.
Writing Functions:
Functions are an important aspect of core JavaScript.Every functions has the below type of look and feel :
function function'sName(arguments)
{
code to be run;
}
The step evolved in writing a function
step1:Declare a function by simply using the word function.
step2:Name the function. For refering the function later on you need to use this name .
step3:Give the arguments in the parenthesis. An argument is information ie given directly to the function, arguments can be directly used just like variables
step4:Finally,with in the braces write the code that the function will run.
Your First Function:
function sayhai()
{
alert("Hai");
}
This function will simply generate a pop-up-alert box in the browser displaying on it as 'Hai".
To run this function simply call it by name as sayhai();
Using arguments
Lets make this a little more complex and add your name after the word "Hai".To do this you need to add arguments in your function
function sayhai(name){
alert("Hai" name);
}
sayhai("Asit");
Frames:
Frame helps webauthor to carve the browser window into several sections.This section helps you how to get control over the frames and how to make the developer site more sophisticated.The command frameset divides the screen into two parts.One part is of 140 pixels wide,while the second column will take the other parts of the browser.
ex:
<html>
<head>
<title>This is a Frame Example</title>
</head>
<body>
<frameset cols="140,*">
<frame src="toolbar.html" name="tool">
<frame src="main.html" name="main">
</frameset>
</body>
</html>
Warning :Dont get framed.It means that never try to link to another frameset by your frameset.Otherwise inside one part of the frame the whole frameset will displayed which may create problem to the web surfrer.
One Clicks Many Links
One of the most frequently asked question(FAQ) is that how to change both the frame with one click.i.e clicking the link on the toolbar frame both the main frame as well as the toolbar will have to change.
The JavaScript used for this purpose is that
function changePages(toolbarURL,mainURL)
{
parent.toolbar.location.href=toolbarURL;
parent.main.location.href=mainURL;
}
Rotating Pages:
Frames are the one of the best ways to rotate content.
<html><head><title>This is a rotating Page</title>
<script language="JavaScript">
<--
function rotate()
{
if(currentpage<totalPage)
currentpage++;
else currentpage=1;
parent.rotateFrame.location.href=prefix+currentpage+'.html';
setTimeout('rotate()',1ullTime);
}
var prefix='rotate';
var currentpage=0;
var totalpage=3;
var 1illTIme=1000;
//-->
</script>
</head>
<frameset onLaod="rotate()"cols="30%,70%" frameBorder=no
border=0 framespacing=0>
<frameset rows="*,200" frameborder=no border=0
framespacing=0>
<frame name="little" src="h1.html">
<frame name="rotateFrame" src="h2.html">
</frameset>
<frame name="big" src="h3.html">
</frameset>
</html>
This set up consists up three frames h1,h2,h3.The h2 frame is where the rotated HTML documents are displayed.When the frameset is loaded then immediately a function called rotate() is run.
Forms and Functions:
Create Your own form:
<html>
<head>
<title>A Form</title>
</head>
<body>
<form name="simple">
<input type=text name="stuff" value=" ">
<input type=button value="Okay">
</form>
</body>
</html>
The form always should create starting with the tag <form> and will be ended with the tag </form>. Type can be defined as text, button, radiobutton, checkbox etc. Whenever you referer to anything in JavaScript ,you referer it by name. In most cases, the name of an HTML object is determined by the NAME attributes of its tag. This form's name is simple. It creates a text and the name is stuff where as the other type is a Button one and it does not have a name but has a value of its own called "Okay".
Generally frame are used for the purpose of sending message to the serverside. The frame has two tags known as "Action" and "Methods" which are very useful. The tags "Action" is used for sending information of a page to another page or to a particular server. And the Method tag has two properties those are "Post" and "Get". This will send the information to the page specified at the Action tag.To understand see the below example:
<html><head>
<title>Example </title>
</head>
<body>
<form name="Complex" Action="h4.asp" Method="Post">
<input type=text value=""name="form1">
<input type=checkbox value="" name="yes">
<input type=submit name="submit" value="S U B M I T">
<input type=reset name="reset" value="R E S E T">
</form>
</body>
</html>
There are two buttons named as "submit" and "reset" are defined in the type tag. These two buttons are inbuilt one.They bydefault do some operation. The submit button will submit the content of the page to another page or to the page specified at the tag "Action" in side the form
Where as the reset button will reset all the data from the form.
LEARNING JAVASCRIPT : PART II
LESSON 1
1. Introduction to Window Manipulation
2. Window Manipulation in JavaScript
3. Examples of Opening Windows with JavaScript
4. Windows Features
5. The JavaScript Document Object Model
6. Messing with the Status Bar
7. Communicating between Windows
8. More about the JavaScript Document Object Model
9. Other Properties of Windows
10. More about Window and Frame Hierarchies
1.Introduction to Window Manipulation
Before learning how to open a window in JavaScript, you should know how to open one using HTML. In most recent browsers, you can open a new window using an href statement. For example, clicking on this link will open another window.
The HTML used to do this is:
clicking on <a href="yer_new_window.html" target="yer_new_window">this link</a> will open another window.
The important thing to know about windows opened by targeted links is that the window above now has the name "yer_new_window" associated with it. If you have another href that uses "yer_new_window" as the target, and you haven't closed the window yet, whatever URL you put in that link will open in the original window.
For the purposes of this lesson, I'm going to call the target name, in this case yer_new_window, the name of the window.
Now that we've had this brief refresher on href targets, it's time to learn about opening windows in JavaScript.
2. Window Manipulation in JavaScript
While opening windows in HTML is very handy, it's also limiting; the Web browser controls how the window looks. You have no control over the size of the window or what the window looks like. Happily, JavaScript gives you this control.
Here's how:
window.open("URL","name","features");
This statement opens a window with the URL that you list as the first parameter in the method call. Above it's called "URL," but in an actual call you'd write "http://www.hotwired.com/maya/" or something similar.
The second parameter of the method call is the window's name. This is just like the name we saw in the last page. If you open a window and there's already a window open with the same name, the URL in your open statement will be sent to that open window.
The third parameter, features, is a list of the different components a window can have. It's an optional parameter, so let's do some examples with the first two parameters before checking out features.
3.Examples of Opening Windows with JavaScript
Try clicking on these three links and see what happens. Don't close any of the windows until you've clicked on all three links. Create a window named javascript_1.
Create the second window named javascript_2. And the third window named javascript_1.
Here's the first line:
<a href="#"
onClick="window.open('javascript_window_1.html','javascript_1');">Here's a window named javascript_1</a>.
When you click on this link, a new window called javascript_1 gets opened and the HTML page javascript_window_1.html gets put into the window. Because the features parameter is optional, you can just leave it out. This will give you the default window you would have gotten if you'd
used a targeted href, as in the previous page. Notice that I put the call to open the window in an onClick. You don't have to put window.open() calls inside an onClick, it was just convenient to do so in this example. You'll see examples of window.open() inside <script> tags soon.
The second link is almost exactly like the first link. It just opens a window with a different name and loads in a different HTML page:
<a href="#"
onClick="window.open('javascript_window_2.html','javascript_2');">Here's a window named javascript_2</a>.
The third link sticks a new HTML page into the first window. This works because the third link opens a window with the same name as the first window: javascript_1.
<a href="#"
onClick="window.open('javascript_window_3.html','javascript_1');">Here's another HTML page going into javascript_1</a>.
Now the fun begins. We can play with the features parameter to make our windows look very different.
OK already, let's play with windows features!
4. Windows Features
The third parameter of the window.open() method is a list of features that you'd like your window to have. As you've seen, if you don't include this parameter at all, the window will contain all the features of a default browser window.
However, if you specify any features in the third parameter, just those features will appear. The way to specify that you'd like your window to have certain features is to list them as a comma-separated list.
For example, if you write
window.open("some_url","window_name","location,menubar");
you'll get a window with just the location box (the place in your browser where you type in a URL) and a menu bar (File, Edit, etc.). Note that it's important that you don't put any spaces in the string. This will upset some browsers.
Another example is
window.open("some_url","window_name","location,height=100,width=100");
This will open a window that is 100 pixels high and 100 pixels wide and has no features other than a location field. Notice again that there are no spaces in the string. Here's a list of the features that you can include in the feature string:
menubar
This is the row of functions that appears on most software applications. Normally it includes File, Edit, and a few other items.
status
This is the message bar at the bottom of your window. When you move your mouse over an HTML link, the URL appears in the status bar. You may have seen pages that use JavaScript to turn this status bar into a scrolling marquee. I'm not going to show you how to do this. If you want to know, you have to figure it out yourself.
scrollbars
This allows scrollbars to appear when necessary.
resizable
If resizable is listed, the window can be resized. Be careful of the spelling. I always get it wrong.
width
The width of the window in pixels.
height
The height of the window in pixels.
toolbar
The browser toolbar, which contains the Back and Forward buttons, the Stop button, and the Home button, among others.
location
The text area of a browser into which you can type URLs.
directories
The directories that Netscape browsers have called "What's new," "What's cool," and so on.
Here are some examples of different types of windows.
Once you've checked out the examples, and maybe tried bringing up some windows of your own, it's time to learn how to mess with the contents of the windows.
5. The JavaScript Document Object Model
Now that you know how to open the window of your choice, it's time to learn how to manipulate things inside that window. To really get control over the things that appear in a window, you have to learn about the JavaScript Document Object Model (DOM). And before you learn about the DOM, it helps to learn a little bit about object-oriented programming.
Brief overview of object-oriented programming Object-oriented programming - especially the JavaScript version of it - isn't so hard to understand. The main idea is that information is
organized in terms of objects. JavaScript is wonderful because it comes with a built-in library of objects. For example, a window is an object. Whenever I refer to one of the default JavaScript library objects, I will capitalize it (Window). Specific instances (a particular window)
will be lowercase.
Objects have properties that describe them. Some of the properties of a Window object are its name, the words in its status bar, the URL of the document inside the window, and the window's document itself, which includes the words, images, and hyperlinks inside the window.
In JavaScript, you are given a default Window object called, of all things, window. Here's how you access a property of the default Window:
var the_status = window.status;
This says: "Find the status property of the Window object called window, and load it into the variable the_status." The status property of the Window object contains the words that appear in the status bar. In addition to reading what those words are, you can also set those words.
The way to set an object's property is this:
window.status = "I'm wondering around!";
6.Messing with the Status Bar
Move your mouse over the following two links and keep your eye on the bottom of the page.
Who do we love?
Why do we love them?
Here's the source code for the first link:
<a href="#" onMouseOver="window.status='Monkeys!';">Who do we love?</a>
This says: "When the mouse is moved over this link, change the status bar."
In addition to properties, objects also have methods. Methods are the actions an object knows how to take. For example, Windows know how to open other Windows: window.open("URL,""name,""features"). This tells JavaScript to use the open method of the Window object to open a new window.
So, as in the example above, a method of an object is called the same way that a property is accessed: the object name, a period, and then method. The main difference is that methods are always followed by parentheses that contain the parameters of the method. Even if the
takes no parameter, you still need the parentheses. For example, remember this?
var italic_hippy = hippy_monkey.italics();
Yup, strings are actually objects, and italics() is a method of the String object. You've seen several other examples of Window methods and haven't known it. The dialog box calls alert and prompt are actually methods of the Window object. If you call:
window.alert("Viva la primate!");
You'll get an alert box that reads "Viva la primate!" The reason that we were able to just say alert("Viva la primate!"), as in earlier examples, is because window, being the default top-level object, can be left out.
This means that open("URL","name,""features") does the same as window.open("URL,""name,""features").
I'm not going to go into all the methods of Window objects here, just two more: focus and blur. The focus method moves a window that's behind other windows to the front. The blur method does the reverse - it moves a window behind other windows. Unfortunately, blur and focus don't work with Internet Explorer 3.0 or Netscape 2.0, so again, if you're using either of these, it might be time to upgrade.
Try blurring this window.
It seems sort of silly to just blur the window that you're looking at. In order to use focus and blur more usefully, you need to know how to invoke method calls on other windows.
7. Communicating between Windows
Although it doesn't make sense to blur or focus the window you're on, you might well want to move another window to the fore. In order to communicate with a window using JavaScript, you need a reference to that window. Getting and using a window reference.
There are a few key lines in this JavaScript. First, we open a new window and get a reference to it:
var new_window = window.open("hello.html","html_name","width=200,
height=200");
This opens a little window and assigns the variable new_window to refer to it. Just as variables can contain numbers and strings, variables can also contain references to objects - in this example, a Window object. Now the variable new_window will behave just like the default Window object. You can call methods on new_window just like you could on window.
The next line shows you an example of calling a method on new_window:
new_window.blur();
Not too tricky, it's just like window.blur() from the last page. These two lines appear in the head of the HTML page. View Source on the page if you want to see the whole thing. As I've mentioned, I tend to put my JavaScript code in the head of HTML pages.
That way I can find it when I'm looking for it. These lines of JavaScript could just as easily have gone in the body. Now, moving to the body we see two links that will move the new window forward or backward:
<a href="#" onMouseOver="new_window.focus();">Bring it forward</a>
<a href="#" onMouseOver="new_window.blur();">Put it backward</a>
Get it? Let's see ... it's time for an exercise. Try writing this extension to the previous window-reference example. This exercise is pretty tricky; to get it working, you'll have to figure some things out. But give it a try before you View Source to check the answer.
After you're done, come back here and we'll go on to discuss more about the JavaScript Object Model.
8.More about the JavaScript Document Object Model
So far we've learned that JavaScript includes default objects, like Windows. We've learned that objects have properties that describe them, and methods that describe what the objects know how to do. Now it's time to delve a little deeper.One neat thing about objects is that the properties of an object can be objects too. For example, windows have a property called document refers to the actual HTML document in the window. This document property is itself an object that has properties of its own. We saw an example of this when we talked about image swapping. Harkening back to the last lesson, we learned that you can do an image swap like this:
<a href="#" onMouseOver="window.document.the_image.src='button_d.gif';
">change</a>
That long string, window.document.the_image.src='button_d.gif', translates into: "Find the document property of the window, find the_image property of the document, find the src property of the_image, and set it to button_d.gif." Quite a mouthful, eh? It all works because windows are
objects, documents inside windows are objects, and images inside documents are objects too.
It may seem like a lot of detail to keep track of, but actually it's not too bad. The JavaScript Document Object Model describes a small hierarchy of objects.
In these tutorials, we'll be looking at about half of the hierarchy. Most of the juicy stuff relating to making your pages more dynamic involves the document object. The document object is very rich and deserves a lesson on its own. So, for the rest of this lesson, we'll be focusing on some of the other properties of windows.
9. Other Properties of Windows
All the remaining properties of windows that we'll see in this lesson relate to frames and how to use them with JavaScript. After I show you how to play with frames in JavaScript, I'll give you your homework for the day.
In JavaScript, frames are treated just like windows. Just as you can tweak the appearance of one window using JavaScript inside a different window, you can change the look of one frame from another. The important thing to remember about frames is that each frame inside a window is considered to be another window. This can get a little weird, because frames can nest inside
other frames. This means that you have a top window, which contains the first frameset. Each frame in the frameset is really another window. This sets up a hierarchy in which you have a top window containing other windows that can themselves contain other windows. Usually it doesn't get that complicated. Here's a straightforward example of using frames with JavaScript. I'll
break it down line by line. The first thing we need to look at is the frameset.
<frameset rows="25%,*">
<frame src="frames_example_controls.html" name="control_frame">
<frame src="blank.html" name="target_frame">
</frameset>
This is just like any ordinary frameset. The important thing to note and remember is that the frames in the frameset are named. The first frame, called control_frame, holds the HTML page that contains the JavaScript. The second frame, as you can see from the src="#", contains nothing. The second thing to look at is the contents of the control_frame.
To keep things simple, it only has one interesting line:
<a href="#" onClick="top.target_frame.document.writeln('Monkey do!<br>');">Just See </a>
When this line is executed, JavaScript starts with the top of the windows hierarchy, which is the window containing the frameset, and finds the frame called target_frame. Since the frame called target_frame is considered a window, it has a document property. JavaScript finds its document property and calls the writeln() method of the document. This results in the words "Just See" being written to the document. Yes, if you hadn't realized it, writeln() is a method of the ocument object, which is why, in earlier examples, we had to write document.writeln() instead of just writeln().
10.More about Window and Frame Hierarchies
We've seen a couple of instances of built-in variables being used in the last few examples. One of the built-in variables is window. The window variable refers to whatever window the JavaScript is executing in. If you have some JavaScript in a frame and you write window.document.writeln(), the writeln will happen in that frame. People sometimes use the built-in variable called self instead of window. The two (window and self) are interchangable. In the last example, you were introduced to the built-in variable called top. This will always refer to the top-most browser window. If you want to start at the top of the window hierarchy, use top. Another built-in variable is parent, which refers to the window containing the frame you're currently in. If you have a frameset in a window, and one frame contains another frameset, the second frameset can refer to the enclosing frame using the parent variable. This gets a little tricky so I'm not going to go into it, but here's an example of using JavaScript with frames inside frames for you to look over. Check it out or just go
Review
We covered four main topics today: windows, frames, the Document Object Model, and Object-Oriented programming. By now you should know about
Opening windows
How to open windows and make them look the way you want
Communication between windows
How to get JavaScript in one window to affect another window
Communication between frames
How to get JavaScript in one frame to affect other frames
Objects
Objects have properties and methods
The Domain Object Model
A browser window is an object that comprises other objects. If you know the hierarchy of the objects in the DOM you know how to affect aspects of your HTML page. Although we didn't go into all the details of all the objects in the DOM, we did get an idea of how it works. In the next lesson, we'll cover a few aspects of computer programming that haven't been touched on yet. In the fifth lesson, we'll study the DOM further and go into how most of objects in an HTML cument can be accessed and changed.
LESSON-2:
1. Looping Password
2. More about While Loops
3. Nested Loops
4. Arrays and Loops
5. Arrays in the Document Object Model
6. Functions
7. Functions with No Parameters
8. Parameters and Return Values
9. Functions with More Than 1 Parameter
10. Function Program
11. Review
There are two main parts to JavaScript: the syntax of the language and its
library of objects. In Lesson 1, which was an introduction to the syntax, we
looked into variables, statements, and if-then clauses, which are parts of
all programming languages. Now it's time to learn the rest of the JavaScript
syntax. There are only three major aspects of JavaScript syntax that we have yet to cover: loops, arrays, and functions.
1. Looping Password
Let's go through this example line by line. After the typical JavaScript preamble, we start with a couple of variable declarations:
var password="pass the wrench";
var answer;
Here we define the password as a string, and we declare a variable called
answer. You'll see why we had to declare answer in a second. The next few
lines are the important ones:
while (answer != password)
{
answer = prompt("What's the woyd?","");
}
This is a while loop. while loops come in this general form:
while (some test is true)
{
do the stuff inside the curly braces
}
So the above lines say, "While the answer isn't equal to the password, execute the prompt command." The loop will keep executing the statements
inside the curly brackets until the test is false. In this case, the will only be false when the words the user enters are the same as the password (that is, "pass the wrench").
We had to declare answer because performing a test like (answer != password)
on an undeclared variable will give an error in some browsers. Because answer is given a value by the prompt method inside the while loop, it will have no value the first time we hit the loop. Defining it early gives it an initial value of "".
Although looping indefinitely is often useful, loops are more commonly used to execute a set of statements a specific number of times.
2. More about While Loops
You should have seen as many x's as you asked for. Let's go over this:
First, we ask for the number of x's:
var width = prompt("How many x's would you like? (1-10 is good)","5");
Next, declare a few variables:
var a_line="";
var loop = 0;
And now for the important part:
while (loop < width)
{
a_line = a_line + "x";
loop=loop+1;
}
This says, "while the variable loop is less than the requested width of the row of x's, add another x to the line and then add one to the value of loop." This loop will keep adding an x to the line and adding one to the value of loop until loop is no longer less than the requested width. Here's a timeline of what happens when a person chooses two x's at the prompt:
Time 1
a_line = "" (because we initialized it to be "")
loop=0 (because we initialized it to be 0)
width=2 (because that's what the user asked for)
0 is less than 2
so a_line = a_line + "x",
so now a_line = "x" loop=loop+1,
so now loop = 1
Back into the loop:
Time 2
loop=1
width=2
a_line = "x"
1 is less than 2 so
a_line = a_line + "x", so now a_line = "xx"
loop=loop+1, so now loop = 2
Back into the loop: Time 3
loop=2
width=2
a_line = "xx"
2 is NOT less than 2 so
fall out of the loop and do what follows
And what follows is:
alert(a_line);
Throw up an alert box announcing a_line.
This sort of loop is so common that programmers have developed a few shortcuts. Using the shortcuts, the while loop could have been written like this:
while (loop < width)
{
a_line += "x"; //this was a_line = a_line + "x";
loop++; //this was loop=loop+1;
}
The first line, a_line += "x", says "add x to myself." This shortcut works with numbers, too. If you have a_number = 5, and you write, a_number+=3, it's just like writing a_number=a_number+3. Programmers are lazy; they're always coming up with shortcuts like this.The next line, loop++, means "add one to myself." So, loop++ is the same as loop=loop+1, which could also be written loop+=1. Each of these is equally good. Which one you use depends on how lazy you are.
Just like there's more than one way to add 1 to a number, there's more than one way to write a loop. while loops aren't the only kind of loops out there. Another popular one is the for loop.
3. Nested Loops
Here's the script:
var height = prompt("How high do you want the grid? (1-10 is good)","10");
var width= prompt("How wide do you want the grid? (1-10 is good)","10");
var a_line;
var new_window =
window.open("/webmonkey/98/04/files1a/grid.html","looper","width=400,
height=400");
new_window.document.writeln("<h1>A Grid</h1>");
for (height_loop = 0; height_loop < height; height_loop++)
{
a_line = "";
for (width_loop = 0; width_loop < width; width_loop++)
{
a_line+="x";
}
new_window.document.writeln(a_line + "<br>");
}
After asking for height and width, opening a new window, and writing a header to it, we go into a for loop. The first for loop sets a_line = "". Try doing the example without this line and see what happens. After initializing a_line, the script goes into another for loop to build a line of x's as wide as required and prints it out the new window. This happens height times. OK, here's your assignment: Take a look at this loop exercise and try doing it on your own before viewing source to see how it works.
4. Arrays and Loops
Arrays are great, because you can loop through each element of the array and do something with it. Here's an example of arrays and loops that presents a URL slide show. Take a look at the slide show and then come back here. The first thing we do to make the slide show work is declare some variables:
var url_names = new Array("hits.org","awaken.org","bianca.com");
var a_url;
Next, we loop through the array, opening each URL and waiting for the user to click on the alert OK button:
for (loop = 0; loop <url_names.length; loop++)
{
// make the name of a url, for example http://www.hits.org/
a_url = "http://www." + url_names[loop] + "/";
// open a window
var new_window=open(a_url,"new_window","width=300,height=300");
// wait for the click
alert("hit ok for the next site");
}
There are a few interesting things in this loop. First, note that the loop goes from 0 to something called url_names.length. Putting .length after the name of an array tells you how many elements are in the array. Remember, however, that this number is not the same as the index number of the last element in an array. If an array has three elements, its length is 3 but its last element is array[2]. This is because the first element of an array is array[0]. If you're getting errors like " not found" and there's an array in your code, you may well have mixed the index number of the array element with the overall number of elements in the array.
You might have noticed that putting a .length at the end of an array looks
a lot like finding a property of an object. Well, that's because arrays ctually are objects and length is one of the array's properties.The other sign that arrays are objects is that you create a new array using the new command. In the above example, url_names = new Array("blah","blah"...) actually says, "make a new array and make url_names a
reference to it." In general, that's how you create a new instance of an object. We won't be going much deeper into objects for this set of lessons, so, for now, just keep in mind that if you see the word "new" being used in this way, you're looking at an object being created. The first line in the loop just creates a variable that holds a string.
a_url = "http://www." + url_names[loop] + "/";
The first time into the loop, the value of the variable loop is 0. The first element in the url_names array is the string "hits.org". So, during the first time in the loop, the variable a_url will equal the string "http://www.hits.org/".
The next line of the loop opens a window with that URL.
var new_window=open(a_url,"new_window","width=300,height=300");
Because each time we open the window we give it the same name, we won't get multiple windows. If we had left out the name "new_window" we would have opened a different window each time we went through the loop. The third line of the loop simply throws up an alert box and waits for the user to hit the OK button.
There are more uses for arrays than just holding strings. In fact, it turns out that arrays run throughout the JavaScript Document Object Model. Here's an example of the role of arrays in the DOM.
5.Arrays in the Document Object Model
This example is going to use image swapping to show how arrays are into the DOM. If you have Internet Explorer 3 or Netscape Navigator 2, you should upgrade. Try the example, View Source, and read on.
Here's the JavaScript that's in the onClick="" in the link:
var change=prompt('Change which image (0 or 1)?','');
window.document.images[change].src='three.jpg';
The first line gets a number and the second line does the change. In the past, we changed images using something like
document.image_name.src = 'some_image.gif';
In order to do this, each image has to be named. If you don't know name of an image that you want to swap, but you know its order on the HTML page, you can refer to the image by its DOM number. The first image in an HTML document is document.images[0], the second is document.images[1], and so on. If you want to know how many images are in a document, you can find out by checking the length of the images array: document.images.length. For instance, if you wanted to change all the images on your page to a spacer GIF, you could do this:
for (loop = 0; loop < document.images.length; loop++)
{
document.images[loop].src = 'spacer.gif';
}
Spiffy, huh?
OK, there's one more part of JavaScript syntax you need to know before you can consider yourself a full-fledged programmer: functions. Once we cover functions, we'll do a few exercises, and then I'll give you your homework for this lesson.
6. Functions
Functions are the last bit of basic programming you need to know before you can understand and perform your own serious JavaScripting. All programming languages have functions. Functions, or subroutines, as they're sometimes called, are bits of JavaScript that you can call over and over without having to rewrite them every time. Let's say you were trying to teach yourself to speed read and you wanted to sprinkle a long text with links which, when hit, would tell you the current time.
For example ... time!
Here's the JavaScript that does this:
<a href="#" onClick="
var the_date = new Date();
var the_hour = the_date.getHours();
var the_minute = the_date.getMinutes();
var the_second = the_date.getSeconds();
var the_time = the_hour + ':' + the_minute + ':' + the_second;
alert('The time is now: ' + the_time);">time!</a>
The details of how this little JavaScript works aren't really important right now; I'll go over them soon. The important thing to notice is that it's fairly long. If you wanted to have 10 of these time links, you'd have to cut and paste this script each time, making your HTML pretty long and ugly. In addition, if you wanted to change the script, you'd have to change it in 10 different places.Instead of having 10 copies of it on your page, you could write a function to execute the JavaScript. That way you'd have the function in one place, making it easier to edit and easier to read.
Here's how you'd write a timer function.
7. Functions with No Parameters
This HTML page contains a function called announceTime(). To call announceTime from a link you'd do this:
<a href="#" onClick="announceTime();">time!</a>
Like so ... time!
You saw something like this in the second lesson:
<a href="#" onClick="alert('Hello!');">Hello!</a>
This was calling the alert method from a link. A function is just like a method, the only difference being that a method is attached to an object. In the case of alert, the object is a Window object. Let's go on to the function itself. If you View Source, you'll see the function sitting in the head of the HTML document. Here it is:
<html>
<head>
<title>Function with No Parameters</title>
<script langauge="JavaScript">
<!-- hide me
function announceTime()
{
//get the date, the hour, minutes, and seconds
var the_date = new Date();
var the_hour = the_date.getHours();
var the_minute = the_date.getMinutes();
var the_second = the_date.getSeconds();
//put together the string and alert with it
var the_time = the_hour + ":" + the_minute + ":" + the_second;
alert("The time is now: " + the_time);
}
// show me -->
</script>
</head>
<body>
...
</body>
</html>
OK, let's go over this function line by line. First, all functions come
in this format:
function functionName(parameter list)
{
statements ...
}
Functions' naming rules are the same as those for variables. The first character has to be a letter or an underscore. The rest of the characters can be numbers or dashes. Also, you must make sure you don't name a function the same as a variable. If you do, you'll get really strange, hard to debug, results. I use internal capitalization for my function names to make sure I don't accidentally name a function and a variable the same thing.
After the function name comes a list of parameters. This function has no parameters, so I'll hold off describing parameters until the next example.
After the parameters comes the body of the function. This is the set of statements you want to run when the function is called. I'm going to use this timer for the next few examples, so let me describe how it works.
The first line
var the_date = new Date();
gets a new date object. Just like you have to get a new array object before you can do anything with it, you need to get a new date object before you can find out what time it is. When you get a new date object, it is automatically preset to the current date and time. In order to get the information out of the object, you have to use the object's methods:
var the_hour = the_date.getHours();
var the_minute = the_date.getMinutes();
var the_second = the_date.getSeconds();
These methods get the appropriate numbers from the date object. You might be asking yourself, how am I supposed to know what methods a date object knows? How do I even know there's such a thing as a date object? Well, these are reasons you need to have access to a JavaScript library. I'll do my best to explain as many of the built-in JavaScript objects as I can, but there's no way I can go through all of them. The rest of the function is pretty clear. It takes the numbers returned by the method calls, turns them into a string, and calls the alert method to put up a dialog box with the string. Note that you can call methods and functions from within functions. We'll see a lot more of this.
Now, if you've played with the time link enough, you might have noticed something isn't quite right. Every once in a while you get something like this: "The time is now: 12:14:4". What's the deal here?
Well, it turns out that the getSeconds() method returns a number. If it's 12:14:04, getSeconds() will return the value 4. Then when we do the string concatenation, the_minute + ":" + the_second, we get 14:4 instead of what we want. There's an easy way out of this, and that's to make a new function that fixes the minutes and seconds if they need fixing. This new function will demonstrate parameters and return values, two crucial parts of functions, so it deserves a page of its own.
8. Parameters and Return Values
Although functions with no parameters are pretty handy for cutting down on the amount of typing you have to do and help make your HTML look better, functions that take parameters are far more useful.In the last example, we had a problem when the getMinutes and getSeconds methods of the Date object returned numbers less than 10. We wanted them to come out as 04 instead of just 4.
We could have done something like this:
var the_minute = the_date.getMinutes();
if (the_minute < 10)
{
the_minute = "0" + the_minute;
}
var the_second = the_date.getSeconds();
if (the_second < 10)
{
the_second = "0" + the_second;
}
This would work fine. Notice, however, that we're basically writing the same code twice: If something is less than 10, stick a "0" in front of it. When you start to notice that you're writing almost the same exact code a bunch of times in your JavaScript, you should start thinking about writing a function to do it. In this case, I wrote a function called fixNumber:
function fixNumber(the_number)
{
if (the_number < 10)
{
the_number = "0" + the_number;
}
return the_number;
}
fixNumber takes one parameter, called the_number. A parameter is just a variable that gets set when the function is called. In this case, if we call the function like this:
var fixed_variable = fixNumber(4);
the parameter the_number gets set to 4 in the function. The body of fixNumber should make sense to you by now. It says, "if the variable the_number is less than 10, add a 0 to the front of it." The only new thing is the return command: return the_number. The return command is used when you say something like
var some_variable = someFunction();
The variable some_variable gets set to the value returned by the someFunction() function. In fixNumber, I wrote: return the_number. This exits the function and returns the value of the_number to whatever variable is waiting to be set. So, if I write
var fixed_variable = fixNumber(4);
the_number will be initially set to 4 by the function call. Then, because 4 is less than 10, the_number will be changed to "04". Then the_number is returned, and the variable fixed_variable will be set to "04." To include fixNumber in original function, announceTime(), I've made the following additions:
function announceTime()
{
//get the date, the hour, minutes, and seconds
var the_date = new Date();
var the_hour = the_date.getHours();
var the_minute = the_date.getMinutes();
var fixed_minute = fixNumber(the_minute);
var the_second = the_date.getSeconds();
var fixed_second = fixNumber(the_second);
//put together the string and alert with it
var the_time = the_hour + ":" + fixed_minute + ":" + fixed_second;
alert("The time is now: " +the_time);
}
Let's say it's 12:04:05 when the time link is clicked on. We get the date
using new Date(), get the hour using getHours(), which doesn't need fixing,
get the minute as we did before, which in this case will be the number 4,
and then call fixNumber on the_minute:
var fixed_minute = fixNumber(the_minute);
When fixNumber() is called, the parameter the_number gets set to the value of the_minute. In this example, since the_minute is 4, the_number will be set to 4. Once the parameter is set, we go into the body of the function. Since 4 is less than 10, the_number is changed to be "04". Then the_number is returned, using the return command. Once "04" is returned by fixNumber, the variable fixed_minute will equal "04". Once you get this working, it should look like this!
Let's go through this step by step and then do an exercise. Assume the
time is 12:04:05.
We start in function announceTime()
the_minute = the_date.getMinutes();
Now the_minute = 4
fixed_minute = fixNumber(the_minute);
Call the fixNumber() function and return its value to fixed_minute Now we're in function fixNumber()
function fixNumber(the_number)
fixNumber() is called with the value of the_minute, which is 4, now
the_number = 4
if (the_number < 10) {the_number = "0" + the_number;}
Since 4 is less than 10, the_number now equals "04" return the_number
The function exits and returns "04"
Function fixTime() has exited, so we're back in announceTime()
The function returns with "04" So fixed_minute now equals "04"
This example used a function which only had one parameter. You can actually have as many parameters as you'd like. For example, here's a function that takes two arrays and returns a list of elements the arrays have in common.
9.. Functions with More Than 1 Parameter
Here are the arrays I've defined:
var monkeys = new Array("mattmarg","wendy","kristin","tim","aaron", "luke");
var kittyphile = new Array("wendy", "ruby", "roscoe", "tim");
var discophile = new Array("mattmarg", "john travolta", "wendy");
var happy = new Array("tim", "wendy", "stimpy", "aaron");
var cranky = new Array("ren", "mattmarg","luke");
With these arrays defined, and the arrayIntersect function written, it's very easy to figure out which Webmonkeys love disco: dancing monkeys. Note that even though John Travolta loves disco, he's not on the monkeys list, so he's not a dancing monkey. To call this function, I wrote
<a href="#" onClick="arrayIntersect('dancing monkeys',monkeys,discophile);
">dancing monkeys</a>
This is a function with three parameters: a string representing the name of the intersection, the first array, and the second array. It's similarly easy to find the names of Webmonkeys who like cats: cat-loving monkeys.
Like so:
<a href="#" onClick="arrayIntersect('monkeys who love cats',monkeys,
kittyphile);">cat-loving monkeys</a>
Let's look at the arrayIntersect function itself:
function arrayIntersect(intersect_name, array_1, array_2)
{
var the_list = "";
for (loop_1 = 0; loop_1 < array_1.length; loop_1++)
{
for (loop_2 = 0; loop_2 < array_2.length; loop_2++)
{
if (array_1[loop_1] == array_2[loop_2])
{
the_list = the_list + array_1[loop_1] + " ";
}
}
}
alert("the " + intersect_name + " are: "+ the_list);
}
See if you can figure out for yourself what the for loops are doing this example. The important thing to note here is the first line of the function:
function arrayIntersect(intersect_name, array_1, array_2)
This defines a function called arrayIntersect with three parameters.Just like in the earlier example, each parameter is like a variable that gets set when the function is called. So, when this function is called like this:
arrayIntersect('dancing monkeys',monkeys,discophile);
The following assignments are made:
intersect_name = 'dancing monkeys'
array_1 = monkeys
array_2 = discophile
The only thing you have to be careful of is that you call your functions with the right number of parameters. If we had accidentally called arrayIntersect like this:
arrayIntersect(monkeys,discophile);
We would have gotten all kinds of errors. Try it and see what happens. Functions are the basic building blocks of any decent JavaScript, so it's very important that you understand how they work. Here's an exercise to test your knowledge of functions. After you've done the exercise, we'll do one more exercise that combines everything we've learned in this lesson, and then go on to do some more work on our personal browsers.
10. Function Exercise
Here's a snazzy way to give people a chance to go to another URL without having to drag their mouses all the way to the Location window: Where you heading?
The neat thing about this script is that people can type either http://some.address.com or just some.address.com. If they do the latter JavaScript will figure it out and append http:// to the front of what they type. Give it a try. Type www.hits.org and you'll see that the script appends the http:// on the front.
Your assignment, of course, is to do this. You'll need one tip though. To check the first few letters of the typed URL, you need to do this:
var the_first_seven = the_url_they_typed.substring(0,7);
After you do this, the_first_seven will hold the first seven characters of the string typed into the prompt.
Review
Today we finished with the syntax of JavaScript. We've covered, in broad strokes, most of what is covered in an introductory computer science course. If you understood it all, you should go grab a celebratory banana. Here's what you should know by now:
while loops
How to make a while loop loop both indefinitely and a specific number of
times
for loops
How for loops work
Arrays
What arrays are and how to initialize and set them
Arrays and loops
How to use loops to go through arrays (using the array.length property)
Arrays in the DOM
How to use arrays to affect images on your pages (the DOM is packed with
arrays)
Functions
You should know what a function is and how to write and call one
Parameters and return values
Functions get interesting when you can change their behavior based on
parameters and use their results in other parts of your JavaScript
You can now call yourself a junior computer programmer. For the next
lesson, we're going to leave the dry-ish world of JavaScript syntax and
return to the JavaScript Document Object Model. Here we will learn about
how you can use forms to interact with users in powerful and interesting
ways.
LESSON -3
Introduction to Forms
1. Text Field Events
2. Form Handlers
3. Review
1: Text Field Events
Text fields understand onBlur, onFocus, and onChange. The onFocus event occurs when someone clicks inside a text field. onBlur happens when somebody moves out of a text field by clicking outside of it, or hitting "tab." onChange happens when somebody changes what's in the text field
and then moves outside the text field. Try doing these things in the text field and see what happens in the textarea below it.
Here's how this works. The text field looks like this:
<input type="text" name="first_text"
onFocus="writeIt('focus');"
onBlur="writeIt('blur');"
onChange="writeIt('change');">
Each of the event handlers calls the function writeIt(), which I've defined in the header. The header looks like this:
<head>
<title>Text Field Events</title>
<script language="JavaScript">
<!-- hide me
function writeIt(the_word)
{
var word_with_return = the_word + "\n";
window.document.first_form.the_textarea.value +=
word_with_return;
}
// show me -->
</script>
</head>
This should all look pretty familiar to you. The first few lines are the
typical JavaScript preamble and the function definition. The first line
in the body of the function
var word_with_return = the_word + "\n";
initializes a new variable, word_with_return, and sets it equal to the string that was passed into the function concatenated with a "\n". (Remember, the "\n" is standard computerese for "new line.")
The next line
window.document.first_form.the_textarea.value += word_with_return;
says, "set the value of the textarea to its current value plus the new variable." This shortcut was covered when we learned about loops. It's the same as saying
window.document.first_form.the_textarea.value =
window.document.first_form.the_textarea.value + word_with_return;
It just takes less time. So far, we've seen a property of text fields and
textareas (the value) and some events that they can handle. The remaining
thing to know about these elements is the methods that they can handle
blur(), focus(), and select().
Here are some links to show you how focus() and select() work. Beware that
they sometimes stop working after the first time:
Mouseover to focus Mouseover to select
Here are the form and the two links:
<form name="method_form">
<input type="text" name="method_text" size=40 value="Hey, hey, we're the monkeys">
</form>
<a href="#" onMouseOver="window.document.method_form.method_text.focus();
">Mouseover to focus</a>
<a href="#" onMouseOver="window.document.method_form.method_text.select();
">Mouseover to select</a>
Accessing the methods of a text field is just like accessing the methods of any object: object_name.method(). The name of a text field is window.document.form_name.text_field_name. So, to call the focus() method on the text field above, we call:
window.document.method_form.method_text.focus();
That's pretty much all there is to know about text fields and textareas. We're about ready to try the first exercise for this lesson. First, however, there's one more thing you need to know about form handlers before you can do the exercise.
2. Form Handlers
Forms are objects; they have their own methods, properties, and event
handlers. One event handler that you should know about is onSubmit.
onSubmit gets called in two situations: if a user clicks on a Submit
button, or if a user hits Return in a text field. If these actions are
not handled in some way, your JavaScript may behave differently than
expected. Try clicking on Submit below and see what happens.
In Netscape, clicking on an unhandled Submit button generally leads to
reloading the page. In general, you won't want this. In order to block
this behavior, you need to do this:
<form onSubmit="return false;">
<input type="submit" value="Submit">
</form>
Try it:
Generally, return false is a way that JavaScript stops your browser from
doing what it would otherwise do. Another example of this is stopping an
href from going to the URL assigned to it. For example, the link
<a href="http://www.mattmarg.com/" onClick="return false;">mattmarg!</a>
won't go anywhere because you've returned false on the onClick. Click on
this dead link, if you don't believe me.
This may seem like a weird thing to do, but actually it's quite common,
especially in the case of forms. Here's an example of using a form to get
input from a user. Type something into this text field and hit Return:
Who does the monkey love:
Here's the form:
<form name="text_entry_form" onSubmit="monkeyLove(); return false;">
<b>Who does the monkey love: </b>
<input type="text" name="monkey_love" size="40">
</form>
When you hit Return in the text field, the onSubmit handler gets called.
It executes the function monkeyLove(), which changes the value in the
text field.
If the return false wasn't in the onSubmit handler, the function
monkeyLove() would execute, changing the text field, but then the page
would reload, changing the text field back to what it was. To stop this
from happening, you need to have that return false in the onSubmit.
Here's the monkeyLove() function for your perusal:
function monkeyLove()
{
var who_it_is = window.document.text_entry_form.monkey_love.value;
who_it_is = 'The monkey loves ' + who_it_is;
window.document.text_entry_form.monkey_love.value = who_it_is;
}
And here's an example of the same form without the return false, just so
you can see what happens:
Who does the monkey love:
Once you've convinced yourself of the merits of return false, it's time
to try a text-field exercise.
Review
Now that you've mastered the basics of computer programming, it's time to refocus on the Document Object Model (DOM). We've already seen that the DOM hierarchy starts with a Window object. Inside each Window object is a Document object. We'll be spending this lesson going through the Document object and seeing how it can be used to get all kinds of information from your users and to dynamically present new information.
We've already had a good look at one of the properties of the Document object, the Images array. If you remember back to Lesson 3, the first image in a document can be modified by changing its src property. For example,
window.document.images[0].src='some_new_picture.gif';
will change the first image in a document to the GIF calledsome_newpicture.gif.
As you might have guessed, each Image in the Image array is itself an object in the DOM. That's why images[0].src works. It's saying, get the Image object image[0] from the Images array and set its src property. The whole statement above reads in English, "get the document property of this window, get the first image from the document's image array, and change its source property to some_new_picture.gif."
The Image object has lots of other interesting properties. For example, you can have your JavaScript check to see if an image has been completely loaded before doing anything.
Confidential : For Private Circulation only
HTML / DHTML / JAVASCRIPT : PAGE 1