CNIT132

Page 1

name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Book 1: HTML Basics Book for Weeks 1-2:

HTML Basics

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 1: HTML Basics Printed by: Donald Siino Date: Monday, 16 August 2010, 02:39 PM

1 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Table of Contents 1 HTML Introduction 2 HTML and Tags 3 Essential HTML Page Tags 4 Saving and Naming your HTML File 5 Case-Sensitivity and File Names 6 White Space and Other Technical Issues 7 Tag Nesting and the Parent/Child Relationship 8 Formatted Lists 9 Unordered Lists 10 Ordered Lists 11 Resources and URLs 12 Absolute URLs 13 The A (anchor) Tag, Part 1 14 IMG (image) Tag Basics 15 The A (anchor) Tag, Part 2 16 Relative URLs 17 The A (anchor) Tag and the NAME Attribute 18 Heading Tags 19 Attributes 20 Coding Style and Tag Syntax 21 Comment Tag 22 Special Characters 23 PRE Tag 24 Physical Style Tags and Content-Based Style Tags 25 BLOCKQUOTE and HR 26 Miscellaneous HTML Tags 27 META Tag 28 Document Appearance

2 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

1 HTML Introduction Reference in Musciano Book: Ch. 1-4, 6-7 HTML Introduction Once upon a time, the Internet was invented. The Internet was simply a collection of computers, connected together via phone lines, with information copied and shared between many, far-flung storage devices. In case of war, this distributed information system would prevent a single bombing strike from disabling or destroying key systems dependent on the free flow of information. All government, educational, and research institutions were to be connected via the Internet. The Internet was not designed for the business and advertising communities, or even the general public; it was created to serve scientific, educational, and governmental ends. No one foresaw the impact the Internet would have, one day, on business, publishing, entertainment, and the world at large. When the Internet was still a medium primarily for scientists and educators, information was mostly conveyed through digital text, or raw data files; presentation of this data was crude as display devices were fairly primitive and data transmission rates were slow. As the technology improved, some people working at CERN, in Switzerland, developed a slightly more sophisticated language for combining text with pictures and other digital media, which they dubbed "HTML", or "Hyper-Text Markup Language". Not only did HTML provide a language for displaying text and pictures SIMULTANEOUSLY (wow!), it also devised the notion of "hyper-text", clickable words which could be used to summon OTHER digital resources, such as HTML pages, pictures, and sound files. It was felt, at the time, that this would provide scientists and academics with a convenient way to create automated footnotes and tables-of-contents, as well as a more sophisticated means of accessing data files. Within just a few years, HTML, it's "World Wide Web", and the Internet transformed our society, affecting everything from business to entertainment, communication and communities to publishing and pornography. Technological advances on the Internet have moved so quickly that it is easy to lose sight of certain fundamental truths. HTML is, at heart, a structural language. It was designed for scientists and educators, not for print publishing professionals. It is easy to mark-up a list of bullet points. It is simple to mark a paragraph of text. It is child's play to insert a picture, link to another website, or create a spreadsheet-like table of data. It is impossible to create an absolutely 100% consistent appearance for any of these things. Different hardware and display devices, different operating systems, different software, all contribute to variations and inconsistencies in appearance and

3 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

layout which can not be completely reconciled at this time.

What is HTML? HTML (Hyper-Text Markup Language) is a display language, a text-only code which tells a web browser (such as Internet Explorer or Netscape Communicator) how to assemble a web page of text, pictures, and other multimedia content.

How does this work? HTML pages are stored as ASCII (text-only) files on a web server. Pictures, stored as GIF or JPEG files, are also stored on a web server. When an HTML page is called up in a web browser, the HTML code tells the browser where on the web server the pictures are located, and where on the page those pictures are supposed to be displayed. The web browser, armed with this information, goes out onto the Internet, downloads the appropriate pictures, then lays them out in the browser window alongside the coded text.

To state this another way: An HTML page, when displayed in a web browser, looks like a single file containing both text and pictures. In fact, an HTML page with pictures and text is really composed of separate elements: an ASCII (text-only) HTML document containing the text and HTML code, and a separate GIF or JPEG file for each picture.

4 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

2 HTML and Tags HTML and Tags HTML is stored in text-only documents. These documents do not contain any built-in formatting or styles for the text (as you might see in a Microsoft Word document), nor do they contain any actual pictures or other multimedia files. They are just text. Although HTML is text-only, it can contain references to many different kinds of files and multimedia elements; you will see more about how this works as we go along. Above all else, HTML is a text-formatting language. So, how does HTML format text? HTML formats text (and everything else, as well) using something called a TAG. Tags can either mark the beginning and ending of some bit of formatting (such as the start and the end points of a paragraph), or the insertion point for some element (such as a picture, or a line break). Because formatting in an HTML document cannot be stored implicitly in the text itself (as you might find in Microsoft Word), every piece of formatting (bolding, italicization, line breaks, paragraphs, images, multimedia elements, etc) must be marked explicitly using tags. Tags are indicated by the use of the less-than (<) and greater-than (>) signs on your keyboard. The P (paragraph) tag, which marks the beginning and ending of a paragraph of text, looks like this: <p>Here is a paragraph of text.</p>

Here is what that code looks like when loaded into your web browser window: Here is a paragraph of text. Opening tags (which mark the beginning of a piece of formatting) use less-than (<) and greater-than (>) symbols, called "brackets", around the tagname. Closing tags (which mark the end of a piece of formatting) are identical to opening tags, with the addition of a forward-slash (/) character just before the tagname. The generic syntax, then, could be expressed in the following manner: <tagname>Content</tagname>

Not all tags have to open and close in this manner, surrounding content. Some tags simply insert formatting information into the flow of HTML text. For instance, the BR (break) tag inserts a carriage return or line break into text without requiring a closing tag, as in the following example: <p>Here is a paragraph of text.<br> Notice how the line break occurs just there?</p>

5 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Displayed: Here is a paragraph of text. Notice how the line break occurs just there? Here is the same code without the BR tag: <p>Here is a paragraph of text. Notice how the line break occurs just anywhere, if at all.</p>

Displayed: Here is a paragraph of text. Notice how the line break occurs just anywhere, if at all.

6 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

3 Essential HTML Page Tags Essential HTML Page Tags There are a handful of HTML tags which are a required part of every HTML page. This section will outline these required tags, their placement, and their usage. The first tag is HTML. This tag surrounds ALL content on the page, both visible and invisible. The HTML tag tells the web browser that all content displayed between its opening and closing tags should be interpreted as HTML. Everything on an HTML page must lie between the opening and closing HTML tag (with one or two specific exceptions). Example: <html> </html>

There are two additional tags which MUST be a part of every HTML page: HEAD and BODY. They are inserted between the opening and closing HTML tags, as follows: <html> <head> </head> <body> </body> </html>

The HEAD of an HTML page contains mostly invisible, meta, or scripting information. The BODY of an HTML page contains ALL visible content; this includes all text, pictures, headings, lists, animations, sound files, and other multimedia elements. The HEAD contains the brains, so to speak, of the HTML page, while the BODY contains everything else. In addition to the aforementioned tags, every HTML page must have a TITLE tag within the HEAD. This TITLE is displayed in the drag-region of the web browser window once the HTML page is loaded. The TITLE of an HTML page is probably the single most important piece of code in HTML as far as the outside world is concerned; this is because of the manner in which search engines (such as AltaVista or Lycos) use the words in the TITLE as keywords for categorization of your web page in their databases (we'll talk about search engines and TITLEs in a later module). Remember: every page MUST have a TITLE, and that TITLE MUST go in the HEAD! <html> <head> <title>Michael's Doughnut Shoppe</title> </head> <body> </body> </html>

7 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Rule of Thumb: If you can see something on an HTML page within the viewable area of a web browser window, that something MUST lie within the opening and closing BODY tags! There are NO exceptions! If, for some reason, you can NOT get your HTML to display properly when it's placed within the BODY tag, you have undoubtedly made some small syntax error in the code. I emphasize this, because students are always telling me that they couldn't get their code to display properly unless they put some visible thing or other into the HEAD of their HTML page; without exception, they had made a small syntax error in their HTML code which they had overlooked. NO VISIBLE CONTENT may be placed in the HEAD of an HTML page! If it's visible, it goes into the BODY!

8 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

4 Saving and Naming your HTML File Saving and Naming your HTML File Once you have typed the HTML, HEAD, TITLE, and BODY tags into a text-only document, you are ready to save your document and turn it into an official HTML file. These instructions assume that you are using an HTML text-editor or notepad, which all save documents automatically as ASCII/text-only files. Note: If you are using a traditional word processor, such as Microsoft Word, Microsoft Works, or AppleWorks/ClarisWorks, you will need to save your document specifically as a text-only, ASCII, or HTML file from the Save As... choice in the File menu. Warning: Traditional word processors are NOT recommended for HTML coding due to their tendency to add unnecessary information into a text file, or to substitute illegal characters into your code; they may, however, be used for general-purpose content generation in conjunction with an HTML-savvy text editor, once you are more familiar with the potential problems. For now, stick to one of the approved HTML text-editors.

Basic Instructions: 1. Create an HTML page using the HTML, HEAD, TITLE, and BODY tags in a text-only document. 2. "File/Save" or "File/Save As..." your HTML page. 3. Before you can finish saving your HTML page, you must create a file name for your HTML page. This name should always end with the file extension ".htm" or ".html" to indicate that it is an HTML page. Type this file extension EXPLICITLY; don't expect or allow your text editor to do it automatically for you. 4. Choose a specific folder or location on your hard drive where you wish to save your HTML page. Save it there. (NOTE: My standard suggestion is to create a folder, called webfiles, for all of your web files.)

Naming an HTML Page: There are four rules governing the naming of HTML pages: 1. NO SPACES IN THE NAMES! 2. Always end the file name with ".htm" or ".html" 3. Only use characters from a-z, A-Z, 0-9, and _ (underscore). All other characters (including commas, periods (except for the "dot" at the beginning of the dot-extension), tildes, exclamation points, etc) are considered reserved, and are therefore illegal. 4. Always start the file name with a lower-case letter; no numbers or underscore characters are allowed as the FIRST character of the name (although you may use them anywhere

9 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

else in the name). Here are a few things to remember. Your HTML file name MUST end with one of the following dot-extensions: either ".htm" or ".html". This is mandatory; otherwise, your HTML page will not operate correctly while you are editing it, nor will it be served correctly by the web server once you get it up on the Web. The most common dot-extension is ".html"; this is the standard on Unix and Macintosh systems. Windows can also accept this four letter extension name, although older Windows machines prefer ".htm", the three letter extension (a holdover from the DOS underpinnings of the Windows operating system). Both conventions are acceptable on the Web. If you wish to follow the MOST common convention, always name your HTML files with the four-letter ".html" dot-extension. Type the COMPLETE file name into the Save As... dialog box when saving your file, INCLUDING the .htm or .html extension. Many Windows users are accustomed to letting Windows applications add this dot-extension automatically, but this is not an acceptable practice. Some Windows applications will alter the spelling of the final file name if the complete dot-extension is not typed in when the HTML file is saved for the first time. For Macintosh and Unix users, of course, a failure to type in the dot-extension means that the file won't have the dot-extension as part of the file name, and the file will not operate correctly as an HTML page, on a local drive or on a web server. Remember: Unix and Macintosh applications do NOT automatically add the required dot-extension to ANY file name.

Examples of Acceptable File Names: myPage.html myPage.htm index.html this_page.html default.html my_cat.htm laura.html

Examples of Non-Acceptable File Names: my page.html (space in the name!) 1way.html (starts with a number!) blueblood (no dot-extension!) resume.htlm (misspelling of html!) my~way.html (illegal character!)

Note to cross-platform users: If you're going to be transferring a lot of files back and forth between older Mac and Windows

10 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

machines using floppy disks or Zip disks, you'll want to stick to an even more restrictive naming convention: the DOS naming convention for files, called eight-dot-three (XXXXXXXX.XXX). This means that your file names should be restricted to eight letters (or less) dot the three-letter extension (i.e. myname01.htm or goober.htm). Again, the first part of the name MAY be fewer than eight letters, but it may NOT be greater than eight letters. Remember, you must always include the .htm extension, and NO SPACES IN THE NAME! (Current Windows systems are still built on top of a DOS core, and some versions of the crossplatform file conversion utility built into the Macintosh automatically curtails Windows or Macintosh long file names to the DOS eight-dot-three file naming convention when saving onto or reading from a PC formatted disk. If you're transferring files over some kind of crossplatform network or over the Internet, you won't have to worry about this; this is only a problem when using floppies, Zips, or other removable media transferred between older Mac and Windows machines.)

11 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

5 Case-Sensitivity and File Names Case-Sensitivity and File Names Web servers on the Internet treat file names as CASE-SENSITIVE entities; this means that upper-case and lower-case versions of the same letter are NOT the same as far as a web server is concerned. For instance, "MYPAGE.HTML" is not the same as "mypage.html", which are both different from "myPage.html". Exact spelling is ALSO important: "myPage.htm" is NOT the same as "myPage.html". URLs invoke resources which reside on a web server; therefore, URLs are CASE-SENSITIVE. When you are working on your own computer, testing HTML pages from a local hard drive, this case-sensitivity will NOT be apparent. Once you mount your pages on a web server on the Internet, however, you will find that case-sensitivity is CRITICAL. Everyone gets caught by this case-sensitivity issue when they first start publishing on the Web. I hope by mentioning it, that I'll save you some hours of serious frustration. So, don't say I didn't warn you... Computers have always been rather finicky creatures, at best. Careful proof-reading and meticulous (or at least consistent) spellings are essential to functional code, whatever the language. Web browsers are more forgiving of mistakes than most computer programming environments, but this tolerance is deceptive. Firefox and Internet Explorer are not tolerant of the SAME errors; rather, each has its own set of tolerances which are not completely compatible, and which are different from other browsers, such as Opera. The only truly crossbrowser compatible code is error-free and meticulously crafted.

12 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

6 White Space and Other Technical Issues White Space and Other Technical Issues Now that you have made a simple HTML page and formatted some paragraphs of text, we are ready to discuss specific HTML coding practices and other technical issues.

White Space As you may have discovered already, HTML does not recognize ordinary carriage returns as line breaks for text. Example: <p>Hi There. That was a line of text. And this is a line of text.</p>

Here is how the above code would display in a web browser window: Hi There. That was a line of text. And this is a line of text. You can see clearly that the carriage returns that I have placed into the HTML are ignored by the web browser. Anywhere that I want a line break to occur, I must insert a BR tag, as in the following example: <p>Hi There.<br> That was a line of text.<br> And this is a line of text.</p>

Here is that code displayed: Hi There. That was a line of text. And this is a line of text. Ordinary carriage returns are considered to be "white space". White space is a traditional programming term, used to describe anything which generates blank areas in code. White space includes spaces, carriage returns, tabs, non-breaking-space characters, and anything else which is space-like, carriage-return-like, or tab-like. White space has traditionally been used to break up code into clearer, more easily proof-readable constructions. Look at these two examples: Example (no white space): <p>Here is a paragraph of text.</p><p>And another paragraph of text.</p><p>And

13 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

yet another paragraph of text.</p>

Example (using white space): <p>Here is a paragraph of text.</p> <p>And another paragraph of text.</p> <p>And yet another paragraph of text.</p>

Both examples display identically in a web browser window. But doesn't the second example, using white space, look more like three separate paragraphs than the first example does? White space is used to help clarify structure in code, in that and many other ways. Multiple spaces are not displayed as you might expect. Web browsers take all spaces sitting in a row, and display them as ONE space. Example: <p>Here is some space in the code.</p>

Here is how this example displays in a browser: Here is some space in the code. Indented Tags Often, spaces and tabs are used to indent tags; this is done to clarify code structure. Example: <head> <title>Example Page</title> </head>

Example: <p>Here is an <i>italicized</i> word</p>

Here is the above example, displayed (notice how the indents (and other white space) disappear?): Here is an italicized word Carriage returns may be used relatively freely, so long as they separate lines of code or HTML-encoded elements on a page, and do not come inside the brackets (< >) of a tag.

14 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Space characters should be used deliberately, with caution. Extra spaces and tabs, improperly or sloppily placed on an HTML page, can cause display irregularities, so use only those spaces or tabs which are absolutely necessary. Note: a tab character in HTML is a simulation; it is really 4-5 spaces, combined together.

More White Space in HTML Syntax: Use white space carefully; do not use more spaces than you need. Take a look at the following examples of sloppy coding practice, taken from actual student work: <b >bold text< /b> (not permissible) < b >bold text< / b > (not permissible)

Extra, random space in tags, as in the examples above, is considered to be poor coding practice, and may lead to malfunctioning HTML on older browsers. Single spaces may be added to HTML tags when adding ATTRIBUTES. Beware of inserting extra spaces, not only inside of the tags themselves, but AROUND the tags as well. The following example exhibits sloppy coding practice: This is some <i> italicized </i> text that I have typed.

Here is the corrected example: This is some <i>italicized</i> text that I have typed.

Placing extra spaces around tags will create formatting and artifact problems with many HTML tags; avoid the habit now. Carriage returns, as mentioned earlier, may be placed into your HTML relatively freely. However, they may not occur within the < > brackets of an HTML tag, as this is illegal in older web browsers. Here is an incorrect example of carriage returns used as white space: < p > Here is my paragraph of text. Blah blah and all that. < /p >

A Last Note on the P (paragraph) Tag In earlier versions of HTML, the P (paragraph) tag was used in a similar manner to the BR (break) tag, namely, as a means of creating a specialized line break, one which created more space than the BR tag alone. The P (paragraph) tag may only be used to mark paragraphs of 15 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

text, using opening and closing tags; this must be done in order to support CSS and other new standards. Bad Example: This is an incorrectly formatted paragraph.<p>

Good Example: <p>This is a correctly formatted paragraph.</p>

Remember: Always open and close the P tag around your text!

Case Sensitivity HTML4 is a case-insensitive language, which means that you may use either upper-case or lower-case characters in tag names. For instance, <br> is the same as <BR> as far as HTML4 is concerned. XHTML is the next version of HTML, after HTML4. XHTML is a case-sensitive language, with all lower-case tag syntax. In XHTML, all tags must have closing tags. The content and examples in his course reflect HTML4, not XHTML, although it is permissible for you to use XHTML coding for your web pages. For more information on the use of XHTML, please see Chapeter 16 of the textbook. In XHTML, there is only one acceptable way to code the BR tag: <br /> Current web browsers will accept non-standards-compliant code, but not for many more years. The following examples are incorrect, even though they would display correctly in current web browsers: <P>Here is a paragraph of text.</P> <p>Here is a paragraph of text.</P>

I suggest that you code your web pages using only lower-case tag syntax. Corrected example: <p>Here is a paragraph of text.</p>

NOTE: An overview of XHTML and it's rules are given in the next module.

16 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

7 Tag Nesting and the Parent/Child Relationship Tag Nesting and the Parent/Child Relationship or Hierarchy In recent years, HTML has changed, transformed from a simple text markup language into the display language for an object-oriented programming development environment. As a consequence, it is important that you understand a few object-oriented programming terms, and how these terms relate to your coding practices in HTML. An HTML tag marks information; opening and closing tags form a container to hold that information. Think of an HTML tag as a box, then, with an opening tag as a lid, and the closing tag as the box bottom. You may place many kinds of information into the tag/box thus created, including other tags. When you place a tag within the bounds marked by another tag, you are said to NEST the first tag within the second tag; you would do this just as you would NEST one box inside another, or one of those wooden Russian dolls inside another, etc. Here is an I (italics) tag NESTED within a P (paragraph) tag: <p>Here is an <i>italicized</i> word nested within a paragraph.</p>

This nesting indicates something called a "parent-child relationship" between the two tags. In this case, the P (paragraph) tag would be the PARENT object, and the I (italics) tag would be the CHILD object, because the I tag is nested within the P tag. Here is another example of a parent-child relationship: <head> <title>My Page</title> </head>

The HEAD tag is the parent object, and the TITLE tag is the child object. In the same way, a P (paragraph) tag, nested within the BODY tag of an HTML page, would be a child of the BODY parent. Look at this example: <body> <p>Here is one paragraph.</p> <p>Here is another paragraph.</p> </body>

17 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

In the above example, I have two paragraphs nested within the BODY. Both of these paragraph objects are children of the same parent, the BODY. Neither of these paragraph objects is a child of the other. These two paragraphs, then, are SIBLINGS. The only important relationships in object-oriented programming, then, are PARENT, CHILD, SIBLING, and ANCESTOR. Because HTML is the display language for a greater, web-based, object-oriented programming development environment, maintaining clear parent-child-sibling relationships between HTML elements on a page of code is absolutely essential. The following code would be WRONG: <p>Here are <i>italicized words.</p></i>

Are the HTML objects in the above example siblings, or do they have a parent-child relationship? It is impossible to tell because of the improper nesting between the tags. If you think of your HTML tags as boxes, with lids and bottoms, you will remember that you mustn't mix up one box's lid with another box's bottom; they won't work together properly. Here is a common mistake: <html> <head> <title>Reba's Page</title> <body> </head> <p>Here is a paragraph.</p> </body> </html>

Is the BODY supposed to be a child of the HEAD? Is the HEAD a child of the BODY? The relationships are muddied by the transposed tags. Here is another common mistake: <html> <head> <title>Gomer's Page</title> </head> <body> <body> <p>Paragraph!</p> </body> </html>

Why are there two body tags? And only one of them is closing! What is the other one for? It seems obvious that such a thing would be ridiculous, but I've seen this many many times. Here is the corrected example:

18 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<html> <head> <title>Gomer and Reba's Happy Page</title> </head> <body> <p>Here is a paragraph of text with a <b>bold</b> word in it.</p> <p>This page shows clear parent-child relationships! Hallelujah!</p> </body> </html>

No matter which tags you're using, it's important that their parent/child/sibling relationships are clear; to ensure clarity, tags MUST be nested in a rational manner. Well-Formed Example: <p>Here is an <i>italicized...</i></p>

I opened the I tag within the confines of the P tag, which meant that I also had to CLOSE the I tag within the confines of the P tag! Always make certain that your parent-child relationships are clear! Properly nested tags and parent/child/sibling relationships (also called the parent-child hierarchy) are a part of properly formed HTML syntax, and are vital to the operation of many technologies, including CSS, the DOM, DHTML, XHTML, XML, etc.

19 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

8 Formatted Lists Formatted Lists A formatted list is: A series of bullet points on some topic, or a list of steps or tasks to perform, or a sequence of definitions in the dictionary. In basic HTML, lists are entirely structural, marked with tags; the layouts or bullet points or numbering systems are created entirely by the web browser, using built-in resources, based on the tags in use. Here are some examples: An Unordered List: Apples Fuji Golden Delicious Macintosh Oranges Valencia Navel Grapes Concord Zinfandel Gewurztraminer An Ordered List: 1. 2. 3. 4. 5.

Do the laundry Take out the garbage Feed the animals Dust the living room Turn on the computer a. Check email b. Surf the Internet c. Buy books 6. Take nap A Definition List (rarely used): Recitando Declamatory; in a spoken manner. Religioso In a devotional, religious manner. Replicato Repeated. Rhapsody A wild free composition. 20 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

HTML is a structural language, defining WHAT things are, not what they look like; lists, accordingly, have been pretty plain looking. If you refer to articles discussing lists published by web "experts", however, you will see excessive (and illegal) insertion of extraneous BR tags, FONT tags, and other non-essentials placed into the HTML code in an effort to dress up the list a bit. This is NOT a good idea.

21 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

9 Unordered Lists Unordered Lists Unordered or bulleted lists are probably the most common formatted list used on the Web today. They are quite simple to construct, using two tags: UL and LI. UL stands for "Unordered List", while LI stands for "Line Item". An entire list is contained within the opening and closing UL tags, and each bulleted point is enclosed within an opening and closing LI tag, as follows: <ul> <li>Point 1</li> <li>Point 2</li> <li>Point 3</li> </ul>

The above example would look like this when displayed in a web browser: Point 1 Point 2 Point 3 You may create sub-points for items on your list by using a nested unordered list; I've marked the nested list with comment tags, just to make the nesting clearer (you probably wouldn't need to mark the nested list with comments in the real world): <ul> <li>Point 1</li> <li>Point 2</li> <!-- begin nested list --> <ul> <li>Point 2.1</li> <li>Point 2.2</li> </ul> <!-- end nested list --> <li>Point 3</li> </ul>

This is how the above example would look in your browser: Point 1 Point 2 Point 2.1 Point 2.2 Point 3 UL has one important attribute: TYPE. The TYPE attribute may be used to specify which type of bullets the list will display. There are three bullet types: disc (a regular bullet), circle (a hollow circle), and square (a hollow square).

22 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Tag: UL Attribute: TYPE Values: disc, circle, square Description: The TYPE attribute allows one to set the bullet type for an unordered list. Example Opening UL Tag: <ul type="square"> By default, the main bullet points will come up with discs, the secondary (nested) bullet points will come up with circles, and the tertiary (nested within nested) bullet points will come up with squares. Here's an example list, illustrating the three default bullet types: <h3>Reasons Why Our Boss is a Dud</h3> <ul> <li>He's Ugly</li> <li>He's Stupid</li> <ul> <li>We tested his IQ at 80</li> <li>He can't read words of more than two syllables</li> </ul> <li>He's Annoying</li> <ul> <li>He lobbed grenades at Greta last week</li> <li>He snarled when asked about his gum disease</li> <li>He forced us to watch "Funny Lady" five times</li> <ul> <li>which was boring</li> <li>and cruel</li> <li>and unusual punishment</li> </ul> </ul> <li>He makes Frankenstein seem Sophisticated.</li> </ul>

Displayed:

Reasons Why Our Boss is a Dud He's Ugly He's Stupid We tested his IQ at 80 He can't read words of more than two syllables He's Annoying He lobbed grenades at Greta last week He snarled when asked about his gum disease He forced us to watch "Funny Lady" five times which was boring. and cruel and unusual punishment He makes Frankenstein seem Sophisticated. Here is the same list, using the TYPE attribute in the UL tags to mix up the types of bullets displayed in the lists: 23 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<h3>Reasons Why Our Boss is a Dud</h3> <ul type="square"> <li>He's Ugly</li> <li>He's Stupid</li> <ul type="disc"> <li>We tested his IQ at 80</li> <li>He can't read words of more than two syllables</li> </ul> <li>He's Annoying</li> <ul type="disc"> <li>He lobbed grenades at Greta last week</li> <li>He snarled when asked about his gum disease</li> <li>He forced us to watch "Funny Lady" five times</li> <ul type="circle"> <li>which was boring.</li> <li>and cruel</li> <li>and unusual punishment</li> </ul> </ul> <li>He makes Frankenstein seem Sophisticated.</li> </ul>

Displayed:

Reasons Why Our Boss is a Dud He's Ugly He's Stupid We tested his IQ at 80 He can't read words of more than two syllables He's Annoying He lobbed grenades at Greta last week He snarled when asked about his gum disease He forced us to watch "Funny Lady" five times which was boring and cruel and unusual punishment He makes Frankenstein seem Sophisticated.

24 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

10 Ordered Lists Ordered Lists Ordered Lists are essentially identical to Unordered Lists except that, instead of bullet points, they use a sequence of numbers or letters. Ordered Lists are created using the OL and LI tags, as in the following example: <ol> <li>Take out trash</li> <li>Wash your hands</li> <li>Leave the room in a huff</li> <li>Pick your nose</li> </ol>

Displayed: 1. 2. 3. 4.

Take out trash Wash your hands Leave the room in a huff Pick your nose

The TYPE attribute for the OL tag determines which type of numbering your list will use. There are five values for the TYPE attribute: 1, A, a, I, i. These values indicate whether your numbering for a particular OL will be with numbers (default), capital or lower-case letters, or upper-case or lower-case roman numerals. Tag: OL Attribute: TYPE Values: 1 (default), A, a, I, i Description: The TYPE attribute allows you to choose the type of numbering or lettering your ordered list will follow. Example (default numbering): <ol> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: 1. 2. 3. 4.

25 of 76

Sit Down Eat Lunch Feel Full Burp

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Example (numbered, which is the same as the default): <ol type="1"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: 1. 2. 3. 4.

Sit Down Eat Lunch Feel Full Burp

Example (capital letters): <ol type="A"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: A. B. C. D.

Sit Down Eat Lunch Feel Full Burp

Example (lower-case letters): <ol type="a"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: a. b. c. d.

Sit Down Eat Lunch Feel Full Burp

Example (upper-case roman numerals): <ol type="I"> <li>Sit Down</li>

26 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: I. II. III. IV.

Sit Down Eat Lunch Feel Full Burp

Example (lower-case roman numerals): <ol type="i"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: i. ii. iii. iv.

Sit Down Eat Lunch Feel Full Burp

Example: <ol> <li>Fold Down Sheets</li> <li>Fluff Pillows</li> <ol type="a"> <li>Straighten Pillow One</li> <li>Lay Pillow Two Asymetrically on Top</li> <li>Adjust Pillow Shams Decoratively<</li> </ol> <li>Slide Under Covers</li> <li>Tuck Up Covers under Chin</li> <li>Snooze</li> </ol>

Displayed: 1. Fold Down Sheets 2. Fluff Pillows a. Straighten Pillow One b. Lay Pillow Two Asymetrically on Top c. Adjust Pillow Shams Decoratively 3. Slide Under Covers 4. Tuck Up Covers under Chin

27 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

5. Snooze Example: <ol type="I"> <li>Fold Down Sheets</li> <li>Fluff Pillows</li> <ol type="i"> <li>Straighten Pillow One</li> <li>Lay Pillow Two Asymetrically on Top</li> <li>Adjust Pillow Shams Decoratively<</li> </ol> <li>Slide Under Covers</li> <li>Tuck Up Covers under Chin</li> <li>Snooze</li> </ol>

Displayed: I. Fold Down Sheets II. Fluff Pillows i. Straighten Pillow One ii. Lay Pillow Two Asymetrically on Top iii. Adjust Pillow Shams Decoratively III. Slide Under Covers IV. Tuck Up Covers under Chin V. Snooze Note: Internet Explorer 5 for Macintosh is broken in regards to nested Ordered Lists, causing incorrect numbering for line items. If you wish to support IE5 for Mac, you must NEVER use nested ordered lists. Internet Explorer 5 for Windows does NOT have this problem. You may make your lists start on ANY number (not just 1, A, a, I, or i) by using the START attribute. Tag: OL Attribute: START Value: any number Description: Use the START attribute to set the starting number of your Ordered List (if you wish a sequence to begin anyplace but 1). Example: <ol start="4"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed:

28 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

4. 5. 6. 7.

Sit Down Eat Lunch Feel Full Burp

Example: <ol type="I" start="10"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: X. XI. XII. XIII.

Sit Down Eat Lunch Feel Full Burp

Example: <ol type="A" start="6"> <li>Sit Down</li> <li>Eat Lunch</li> <li>Feel Full</li> <li>Burp</li> </ol>

Displayed: F. G. H. I.

29 of 76

Sit Down Eat Lunch Feel Full Burp

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

11 Resources and URLs Resources and URLs On the Internet, and in programming languages and environments in general, every digital thing is considered to be a resource. HTML or text files are resources, pictures are resources, sound files are resources, Flash animation files are resources; any digital media file is a resource. Resource is a catch-all term for digital media or files of any kind. As was mentioned earlier, HTML pages are really nothing but plain text files/resources which REFER to other types of media for their pictures, animations, etc; all the HTML file itself actually contains is text. A web browser, after reading an HTML file, gathers together the assorted resources (pictures, animations, sound files, scripts, etc) and assembles them into a unified whole for display in the browser window; this display is based on the layout specified in the HTML file. The HTML page invokes (or calls up) its various resources using something called a URL. URL (pronounced Yoo-Arh-Ell) stands for Uniform Resource Locator. A URL is essentially a unique address on the Internet where something is located, either on your local server or anywhere in the world. There are two kinds of URLs: absolute and relative. Absolute URLs point to a specific location on the entire Internet. Relative URLs point to a location on a web server which is in relation to the current HTML page. These differences can be better expressed using real-world metaphors. An absolute URL is like an address with a zip code that you would use to mail a letter; the address points directly to a particular location, and that address doesn't change whether you're mailing the letter from San Francisco or Tokyo or Paris, i.e. "John Smith, 1205 Main Street, Anytown, CA, 93711-9308, USA". A relative URL is like the directions you would give someone from your home or office to get to a particular location, i.e. "go to the corner and take a left, then go three blocks and take another left until you get to the store on the next corner, the package is sitting on the bottom shelf on the right just by the door". An absolute URL points directly to a particular resource on the Internet as a whole, whereas a relative URL gives directions to a resource in relation to your current location. We will discuss absolute and relative URLs in greater detail later in this module. URLs are not only used to invoke pictures and animations on a web page, they are also the foundation of hyper-text or hot-links, the primary means of navigation on the Web; we'll discuss hyper-text/hyper-references in detail later in this module. The Internet is a gigantic database, filled with many different resources. URLs are the means by which some small percentage of these resources can be drawn together, accessed, and utilized via a single web page.

30 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

12 Absolute URLs Absolute URLs An absolute URL represents a unique address on the Internet for any piece of digital media (resource). Absolute URL syntax involves two parts, described in some textbooks as "scheme" and "scheme_specific_part", which must be separated by a colon and described in this manner (NO SPACES): scheme:scheme_specific_part This description, while technically correct, is hardly illuminating. Allow me to explain this to you using ordinary English. When creating an absolute URL, you must specify what type of absolute URL you want, called the "scheme". Is this a web address? Is this an ftp address? Is this a telnet address? These are the questions that are resolved by stating the "scheme". You will be normally be using only two schemes, which are probably the most common types of absolute URLs on the Web: http (Web address) mailto (email address) There are two more schemes which you are likely to see, although we will not be using them in this class specifically: ftp (ftp site address for transfer of files) file (file address on a hard disk or server)

Web Addresses (http) Let us talk specifically of Web addresses (http), since we are most interested in that type of absolute URL. Let us begin by looking at the "scheme_specific_part". Here is the address for the main server at Yahoo, the Web's most prominent search engine: www.yahoo.com

"com" is the domain name. "yahoo" is the sub-domain name (which is commonly called the domain name). "www" is the name of the server in the "yahoo.com" domain. There may be more than one server in a domain, obviously. Netscape, for example, has several: www.netscape.com

31 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

home.netscape.com developer.netscape.com etc. A server is a computer which delivers, or "serves", resources to any computer which requests them. A server which serves resources to computers via an http scheme is called a web server. There are many different types of domains, as well: "com" stands for "company" "org" stands for "organization" "edu" stands for "educational institution" "gov" stands for "government" etc... The "scheme" for a Web address is "http", which stands for "hyper-text transfer protocol". This "scheme" is followed by a colon, then two slashes which form the beginning of the "scheme_specific_part". Thus, web addresses always begin with the following code: http://

The absolute URL for the main server at Yahoo, then, would look like this: http://www.yahoo.com/

"http" is the "scheme". ":" separates the "scheme" from the "scheme_specific_part". "//" is the required prefix for an absolute web address. "www.yahoo.com" represents the server, the sub-domain, and the domain name. "/" is a reference to the root directory on the server. The root directory is the main web folder on the specified server for that domain; there is nothing outside of the root directory which may be served via the Web. The above absolute URL points to the default or index HTML page on the Yahoo site. Thus: http://www.yahoo.com/

is a shorthand for the following: http://www.yahoo.com/index.html

Remember that when you use a URL, you are invoking a resource, which has to be some sort of digital file. Since the first shorthand example didn't explicitly state any text, graphic, animation, or sound resource, the web server at Yahoo had to guess what type of resource was desired. With the http scheme, web servers automatically assume that you are looking for an HTML text resource, namely, an HTML page. Web servers are configured to serve a default HTML page when none is specified. The server software for the web server at Yahoo has been set to serve "index.html" as the default page for 32 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

any directory on the server. Thus, any sub-directory on Yahoo will automatically serve "index.html" if no other page is specified. The Arts area at Yahoo, therefore, could be expressed as either one of the following addresses: http://dir.yahoo.com/Arts/ http://dir.yahoo.com/Arts/index.html

"Arts" is a sub-directory inside the root directory of the "dir" server at "yahoo.com". The index.html page specified here is inside the Arts sub-directory. To put this another way, index.html is an HTML page inside the Arts folder inside the main web folder on the "dir" server at Yahoo. Not every server on the Web has been configured to serve "index.html" as the default page. The three most common default page names are: index.html default.html welcome.html (Note: If NO page in a particular directory has the default page name AND a user invokes an absolute URL to that directory without specifying a page name, the web server will usually deliver an index of ALL of the files in that particular directory to the user.)

A Special Case With the URL, http://hills.ccsf.org/~dadams01, we have a web address which is located on a Unix time-share server. ~dadams01 essentially tells the browser to look for a directory, called public_html, in the home directory of userid dadams01, and display a file called index.html.

Case-Sensitivity and URLs Remember that URLs are case-sensitive. That means that the following URLs are NOT identical: http://www.pge.com/greed/ http://www.pge.com/GREED/

The following URLs are NOT identical: http://www.pge.com/greed/suffer.html http://www.pge.com/greed/Suffer.html

You MUST match case when you type out URLs, which means spelling your URLs with the exact same upper-and-lower-case combinations that appear in the original file or directory name.

33 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Email Addresses Absolute URLs for email addresses involve using the "mailto" scheme mentioned above. The format is simple: "mailto", followed by a colon, followed by the email address desired (NO SPACES!). This would be a mailto URL for my email address: mailto:srubin45@comcast.net

If you type this URL into the location bar of your web browser, you will get a new email message with the appropriate email address pre-typed into the address area. Here are more examples: mailto:csadmin@digidesign.com mailto:somebody_important@apple.com mailto:jobs@lavamind.com

mailto URLs are normally used to create automatic email messages from a hyper-text link on an HTML page. We will discuss creating hyper-text links later in this module.

34 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

13 The A (anchor) Tag, Part 1 The A (anchor) Tag, Part 1 Before I talk about relative URLs, I need to introduce the A (anchor) tag. The A (anchor) tag allows you to create hyper-text references on an HTML page. Hyper-text, hyper-reference, hot-link, these terms all mean the same thing: a clickable link on a page (usually a word or a picture) which invokes another HTML resource. In case you aren't certain what a hyper-reference is, I have given an example below (once you have followed this link, hit the "Back" button on your browser to return). This link invokes the default index.html page at Yahoo using the URL "http://www.yahoo.com/": Yahoo Link Here's the code for the link: <a href="http://www.yahoo.com/">Yahoo Link</a>

Tag: A Attribute: HREF Description: The anchor tag allows you to create an anchor point in the flow of HTML text. The HREF attribute assigns a URL to an anchor tag and makes an active hyper-reference out of the word(s) or picture marked by that tag. Example: <a href="http://www.yahoo.com/">Link Words</a> As mentioned in the above description, the HREF attribute makes the A (anchor) tag operate as a hyper-reference. The value of the HREF attribute must be set to a URL, either absolute or relative. The A (anchor) tag also has another purpose, which we will discuss later. Here is the process for making a hyper-reference: 1. Mark the text or code which you wish to be clickable with the <a></a> tag. 2. Add the HREF attribute to the opening A (anchor) tag, using correct attribute syntax. 3. Set the value of HREF to specify the URL of the desired resource. Here is an example of a paragraph with two hyper-references marked in the text: Hi There. This is a link that will invoke Adobe's default HTML page. Notice how I have marked only the text that I actually wanted hot? I could place a link to Firefox here, as well, which invokes Netscape's default HTML page. In fact, I could put as many hyper-references as I like into this code. Here is the above paragraph as it appears in the HTML code:

35 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<p>Hi There. This is a link that will invoke <a href="http://www.adobe.com/">Adobe's</a>'s default HTML page. Notice how I have marked only the text that I actually wanted hot? I could place a link to <a href="http://www.mozilla.com/en-US/firefox/">Firefox</a> here, as well, which invokes Firefox's default HTML page. In fact, I could put as many hyper-references as I like into this code.</p>

36 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

14 IMG (image) Tag Basics IMG (image) Tag Basics The A (anchor) tag allows us to invoke a resource out on the Web, usually an HTML page, and bring it up in our web browser window, as we have discussed. But A (anchor) tags are not restricted to invoking only HTML resources. Here is a hyper-text reference created using the A (anchor) tag, which invokes a GIF resource; this link invokes "satthumb.gif" which is sitting on my web server: View of Saturn Code: <a href="http://fog.ccsf.org/~srubin/satthumb.gif">View of Saturn</a>

Now, even though we can invoke an image resource using the A (anchor) tag, we can't INSERT an image into an HTML page this way; we can only create a hot-link or hyper-reference TO an image. To actually insert an image/picture into the flow of an HTML page, we need to use the IMG (image) tag. Wherever you place an IMG tag in the flow of HTML, a picture will be inserted. The IMG tag uses a URL to locate a particular image resource on the Internet, gives the web browser information concerning the exact dimensions of the image so that space can be reserved on the page for the picture, and inserts the image into the page at the exact location of the IMG tag in the flow of HTML. Here is an image, inserted into this HTML page:

Here is the code for the above example: <img src="http://fog.ccsf.org/~srubin/satthumb.gif" width="170" height="129" alt="saturn" title="saturn">

Tag: IMG Attributes: SRC, WIDTH, HEIGHT, ALT, TITLE Example: <img src="http://fog.ccsf.org/~srubin/satthumb.gif" width="170" height="129"

37 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

alt="saturn" title="saturn">

Description: Use the IMG tag to insert an image into an HTML document. The SRC (pronounced "source") attribute value must be set to the URL for the image that you want to insert; this URL may be either absolute or relative. This attribute tells the web browser which picture is to be inserted and where that picture is located on the Internet. The WIDTH attribute value must be set to an integer which is the width of the image, in pixels. The HEIGHT attribute value must be set to an integer which is the height of the image, in pixels. Note: The WIDTH and HEIGHT attributes should ALWAYS be set for the IMG tag; a web browser requires these attributes in order to reserve the correct space on the page for the picture. Note: The ALT attribute will allow it's value to pop-up when the user hovers over it, in most browsers except Firefox. The ALT attribute is also required for accessibility of sight impaired persons. The TITLE attribute will pop-up it's value when the user hovers over it in Firefox. I suggest always using both attributes for the IMG tag.

38 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

15 The A (anchor) Tag, Part 2 The A (anchor) Tag, Part 2 As mentioned earlier, you may use A (anchor) tags to mark images as hyper-references, which is done in the same manner as creating a text hyper-reference. Just place an opening and closing A (anchor) tag around your IMG tag, then insert the HREF attribute into the A (anchor) tag and set the value of the HREF attribute to the appropriate URL. Example: <a href="http://www.yahoo.com/"><img src="http://fog.ccsf.org/~srubin/satthumb.gif" width="170" height="129" border="0" alt="saturn" title="saturn"></a> The above example uses our earlier example image, and makes it a hyper-reference to Yahoo. Here is what the above example looks like:

Text Link Example Displayed: Link Word Image Link Example: <a href="http://www.yahoo.com/"><img src="http://fog.ccsf.org/~srubin/capitalA.gif" width="54" height="54" title="Click me" alt="click me"></a>

Image Link Example Displayed:

Notice that the title attribute can be used within the img tag, so that users will see a message when they mouseover the image. Note that the alt attribute will not allow firefox users to see a message when they mouseover the image. The title attribute works the same way for almost all elements on a web page. NOTE: Do NOT put carriage returns inside the brackets (< >) of your tag; the code for one tag

39 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

must all be on a single line (the soft wrap that occurs in text while you're typing doesn't count as a carriage return, of course; only carriage returns that you actually type yourself count). Although carriage returns within tag brackets will eventually be supported, it is not fully supported on all versions of web browsers still in use by the public. This Works now in most Browsers: <img src="http://fog.ccsf.org/~srubin/capitalA.gif" width="54" height="54" >

Correct: <img src="http://fog.ccsf.org/~srubin/capitalA.gif" width="54" height="54">

Finally, a useful attribute to include with the A tag is the title attribute. The value of the title attribute will be displayed in a small box, when the viewer passes their mouse over the link. This will allow you to describe the link more fully to the viewer. The box will disappear after a few seconds. For example: Steve's Homepage The coding is as follows: <a href="http://fog.ccsf.edu/~srubin/" title="See my homepage for lots of HTML examples">Steve's Homepage</a>

40 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

16 Relative URLs Relative URLs A relative URL is essentially a set of directions to a resource from your current location, like directions to the corner store given from your home or office. A relative URL is usually given in terms of the current location of an HTML page, whether it be on the Internet or elsewhere. Relative URLs are, essentially, paths from the current HTML page location to the desired resource. These paths require special prefixes in order to operate correctly, as well as to maneuver through the server's directory structure. There are three prefixes for relative URLs: ./ ../ /

Definitions: Prefix One: ./ (pronounced "dot-slash") Conservative syntax for plain relative URL; it means "look for the resource in the same directory." Example: I am currently on index.html. There is a resource called page2.html in the same directory. Relative URL from index.html to page2.html: ./page2.html

Hyper-reference on index.html using this URL: <a href="./page2.html">Link to Page 2</a>

(NOTE: In most cases the ./ can be omitted and so the above example is virtually the same as) <a href="page2.html">Link to Page 2</a>

Prefix Two: ../ 41 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

(pronounced "dot-dot-slash") This means: "go up one directory level and start looking for the resource." If you need to go up more than one directory level, add one "../" for each directory level you need to ascend. To go up two directory levels and then start looking for the resource: ../../ To go up three directory levels and then start looking for the resource: ../../../ (and so on...) Example (try drawing this out on a piece of paper): I am currently on index.html, which is located in folder "gertrude". "gertrude" is located inside a folder called "harry". "fred" is another folder inside "harry"; thus, fred and gertrude are sibling folders inside the parent, harry. "fred" contains an HTML page called page5.html. Relative URL from index.html to page5.html: ../fred/page5.html

Hyper-reference on index.html using this URL: <a href="../fred/page5.html">Link to Page 5</a>

Prefix Three: / (pronounced "slash") This means: "go to the root directory for the web server and start looking for the resource." A root directory for a web server is the single folder which has been assigned as the "public" web folder; any resource inside this "root directory" may be served to the outside world via the Web; no resources OUTSIDE this root directory may be served via the Web. For instance, the default HTML page in the root directory of Yahoo is invoked when I use the absolute URL, "http://www.yahoo.com/"; on Yahoo's "www" server, the root directory contains everything on the "www" part of the domain.

42 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

17 The A (anchor) Tag and the NAME Attribute The A (anchor) Tag and the NAME Attribute A (anchor) tags allow you to create hyper-references/hot-links to other HTML pages or resources. A (anchor) tags can also allow you to create hyper-references that jump to individual points WITHIN a particular HTML page. Here is an example, which demonstrates this enhanced capability of the A (anchor) tag. By clicking the link, you will arrive at the bottom of the page. To return, hit the back button on your browser. To make this kind of hyper-reference work, you need two A (anchor) tags: One A (anchor) tag to mark the place that you want to jump to, and one regular A (anchor) tag to make the hyperreference. You already know the basics of making regular hyper-references, so let's talk about the A (anchor) tag that marks the "jump-to" point. You must place an A (anchor) tag at each point in the HTML page that you want to be able to jump to. These "jump-to" points are called "NAME anchors", and are created using the NAME attribute in the A (anchor) tag. Tag: A Attribute: NAME Description: The NAME attribute turns an A (anchor) tag into a "jump-to" point, which can be referenced by other A (anchor) tags used as hyper-references/hot-links. Example: <a name="fred">Word</a> Note: Each NAME on an HTML page MUST be unique (no repeats). A NAME anchor MUST surround some content; it may not be placed into a page without marking something; this content will NOT be affected in appearance (e.g., it will not become "hot" or clickable). Here is how some of these NAME anchors might look in code: <html> <head> <title>Some HTML Page</title> </head> <body> <p>Here is the first paragraph of text. This paragraph is not marked.</p> <p><a name="fred">Here</a> is a second paragraph of text. Notice how the first word is marked with an anchor. You could jump to this paragraph, if you wished to.</p> <p><a name="george">Here</a> is a third paragraph of text. Again, you could jump directly to this paragraph on the page because the first word of the paragraph is marked with a NAME anchor.</p>

43 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<p><a name="herbert"></a>This NAME anchor tag is INCORRECT. Notice how the tag is NOT marking content; this usage is not officially supported (although it does work within some browsers). There should always be SOME content between the opening and closing anchor tags.</p> </body> </html>

Remember, these NAME anchors represent "jump-to" points; they are NOT clickable hyperreferences, nor do they alter the appearance of marked content. You can mark anything on an HTML page with a NAME anchor to make it a jump-to point, whether it be text or an IMG tag. Once marked in the HTML code, any hyper-reference may jump directly to a NAME-anchored point by calling that name as the URL, preceded by the pound (#) prefix. For instance, "#fred" would be an appropriate URL for a hyper-reference jumping to the "fred" NAME anchor elsewhere on the same page. Tag: A Attribute: HREF Example: <a href="#fred">Link that jumps to "fred" NAME anchor</a>

In the following example, I have created a pair of hyper-references at the top of the page which can jump to the NAME-anchored paragraphs further down in the code. Example: <html> <head> <title>Some HTML Page</title> </head> <body> <p><a href="#fred">Link to fred</a></p> <p><a href="#george">Link to george</a></p> <p>Here is the first paragraph of text. This paragraph is not marked.</p> <p><a name="fred">Here</a> is a second paragraph of text. Notice how the first word is marked with an anchor. You could jump to this paragraph, if you wished to.</p> <p><a name="george">Here</a> is a third paragraph of text. Again, you could jump directly to this paragraph on the page because the first word of the paragraph is marked with a NAME anchor.</p> </body> </html>

You may also make hyper-references that jump to the TOP of a page. You don't need any

44 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

special NAME anchor to mark the top of the page, however. All you need to do is use the pound (#) sign, all by itself, as the value for the HREF attribute in the A (anchor) tag. Example: <a href="#">This link will jump to the top of the page</a>

Note: This functionality is broken on Internet Explorer 5 for Macintosh. Therefore, you may need to create a NAME anchor at the top of the page, which you may then jump to, just as you would any NAME anchor. <html> <head> <title>Example Page</title> </head> <body> <h1><a name="top">Heading Words</a></h1>

paragraphs of content...

<p>Here is a <a href="#top">link to the top</a>.</p> </body> </html>

You may also jump to NAME anchors that exist on OTHER HTML pages, using either absolute or relative URL syntax. Simply take the absolute or relative URL, and append the pound (#) sign, followed by the name of the NAME anchor that you want to jump to, to the end of the URL. Example: <a href="./page2.html#bill">Link to "bill" NAME anchor on page2.html</a>

Bottom of Page

45 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

18 Heading Tags Heading Tags Earlier, I showed you how to mark plain paragraphs of text in HTML using the P tag. Example: <p>Here is a paragraph of text</p> <p>Here is another paragraph of text.</p>

Paragraphs alone are not enough to lay out text, of course. When you want to create headings in the course of text, you will use variations on the H, or heading, tag. Headings would be used to label sections or subsections in a document; you've already seen headings at work in this very page. Here's an example: <h2>Important Stuff</h2> <p>Look at this area! We are filled with important stuff!.</p> <h3>More Detailed Stuff</h3> <p>This sub-section is filled with more detailed stuff!</p> <p>Look at all the paragraphs which are needed to describe this more detailed stuff. This must be very very important stuff, too!</p> Here's what the above example would look like:

Important Stuff Look at this area! We are filled with important stuff!

More Detailed Stuff This sub-section is filled with more detailed stuff! Look at all the paragraphs which are needed to describe this more detailed stuff. This must be very very important stuff, too! Tags: H1, H2, H3, H4, H5, H6 Description: Creates headings and sub-headings for a document. Always closes.

46 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Example: <h2>Important Stuff</h2>

There are six heading tags: H1, H2, H3, H4, H5, and H6. H1 has the largest font size, H6 has the smallest font size. Heading tags automatically make text bold, and align to the left of an HTML page, just as paragraphs do. Heading tags automatically create line spacing following themselves; this following space grows smaller as the H tag numbers grow larger. Heading tags don't require extra BR tags to set themselves off from surrounding materials; they do this automatically as well. Heading tags ALWAYS close. Heading tags and paragraph tags are the workhorses of everyday HTML coding. Almost every page on the Web contains headings and paragraphs of one sort or another. Don't be concerned that these tags have limited variety in layout; right now, we're just learning about them in their default states. We'll learn more about controlling the position and appearance of heading and paragraph tags in later modules.

47 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

19 Attributes Attributes We can use attributes to change the BEHAVIOR of a tag, as with the ALIGN attribute for the paragraph, div, and heading tags. Some examples: <p align="right"> <div align="left"> <h2 align="right">

We can also use attributes to change the APPEARANCE of a tag. Tag: BODY Attribute: BGCOLOR Values: color values (named colors or hex codes) Description: The BGCOLOR attribute in the BODY tag can be used to set the background color for the BODY of an HTML page. Tag: BODY Attribute: TEXT Values: color values (named colors or hex codes) Description: The TEXT attribute in the BODY tag can be used to set the text color for all content in the BODY of an HTML page. The BODY tag, which represents the visible "document" of a web page, may be modified to have a specific background color using the BGCOLOR attribute. In the following examples, you could also use the hex values of the colors instead of the color names. Many web designers prefer this. For example, black is #000000 and yellow is #ffff00. Example: <body bgcolor="white">

This is how this code would look in an HTML page: <html> <head> <title>Test Page</title> </head> <body bgcolor="white"> <p>The background color of this page has been set to white.</p> </body> </html>

I could set a black background simply by changing the BGCOLOR attribute's value. Example:

48 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<html> <head> <title>Test Page Two</title> </head> <body bgcolor="black"> <p>Now this content is on a black background.</p> </body> </html>

You will not able to read the text in the above example when you viewed it in your web browser. Your browser's text color is probably black, which is the default color for TEXT set in the preferences for your web browser; black text on a black background has VERY low contrast indeed! To rectify this, we could set the text color for the page using the TEXT attribute for the BODY tag. If I wanted a black page with yellow text, for example, I could set both the BGCOLOR and TEXT attributes for the BODY tag. Example: <html> <head> <title>Test Page Three</title> </head> <body bgcolor="black" text="yellow"> <p>This text is yellow on a black background.</p> </body> </html>

Attributes may be added in any order to a tag. The following example works identically to the previous example. <html> <head> <title>Test Page Four</title> </head> <body text="yellow" bgcolor="black"> <p>This text is still yellow on a black background. Attributes may be placed into a tag in any order; switching the attribute order makes no difference to a web browser.</p> </body> </html> You may add as many attributes to a tag as you desire; there is no limit. However, you may NOT repeat the same attribute twice in the same tag! When you add attributes to a tag, you must NEVER restate those attributes in the closing tag. I mention this again because it is a common misunderstanding for many students. The following would be INCORRECT: <html> <head> 49 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<title>Test Page Five</title> </head> <body bgcolor="black" text="yellow"> <p>This text is still yellow on a black background. Sadly, this page is technically incorrect because I have restated the attributes in the closing tag; never do this, as the page may operate incorrectly.</p> </body bgcolor="black" text="yellow"> </html> Notes on Attribute Syntax As mentioned before, every attribute must follow this syntax: attributename="value" This syntax illustrates the strict XHTML standards, which requires that EVERY attribute be identical in form. HTML4, however, is more relaxed about attribute syntax. You will often see attributes with the quote marks omitted in HTML4 pages. Be aware that leaving out quote marks will not be permitted once the XHTML standards are firmly in place. So, I suggest that you ALWAYS use quote marks surrounding attribute values. Note about Quote Marks When we talk about quote marks in HTML and other programming languages, we really mean "straight" quote symbols, not the curly or "smart" quotes that are substituted for straight quotes by most word processors. Curly quotes are not recognized by web browsers and must NEVER be used, as they will break your HTML page. Use straight quote marks: " " Never use curly or "smart" quote marks: “ � Microsoft Word and many other standard word processing programs will automatically replace straight quotes with curly quotes as you're typing, so be careful. The straight quote key is the usual one, right next to the "Enter" key on the PC, or the "Return" key on the Macintosh. Debugging Note The most common reason for student web pages to break or operate incorrectly is a missing quotation mark surrounding an attribute value. If you forget to place one quotation mark around an attribute value, your page may display strangely or the whole page may fail to operate. Therefore, if you run into problems, check for missing quotation marks FIRST; that's what I do. The following example would be incorrect and would probably break the page:

50 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<body bgcolor="white>

If you leave out BOTH quote marks in the above example, the page will operate correctly: <body bgcolor=white>

The above syntax, however, does not conform to the latest standards, and will not be supported in the future. Therefore, you must ALWAYS use both quotation marks surrounding an attribute value: <body bgcolor="white">

The above examples correctly express how attribute syntax operates. However, be aware that, as of HTML 4.0, all appearance information for an HTML page has been removed from the HTML tags themselves and placed in Cascading Style Sheets (CSS). The sorts of background and text color attributes cited in the examples, therefore, would not be used in BODY tags on websites which have implemented the newer standards. I chose to use ALIGN, BGCOLOR, and TEXT attributes as examples because they do something readily comprehensible, but I also want you to know that they are on the way out. We will discuss the details of CSS and document appearance in later modules.

51 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

20 Coding Style and Tag Syntax Coding Style and Tag Syntax In HTML, there is good coding style, there is bad coding style. Good coding style is illustrated in the first and second examples following; weak coding style is illustrated in the third example following, and bad coding style is illustrated in the fourth example following. Tags should either mark content like this (Style 1): <tagname> Content </tagname>

Or like this (Style 2): <tagname>Content</tagname>

Don't do this (Style 3 -- Weak): <tagname> Content</tagname>

Or this (Style 4 -- Bad): <tagname>Content </tagname>

Style 1: Use for tags marking structure, such as BODY, HEAD, TABLE, FORM, MAP, etc. Style 2: Use for tags formatting text or pictures, particularly A, P, B, I, etc. Style 3 -- Weak: This syntax will operate correctly for MOST tags (except P), but it proves hard to debug when code becomes complex and is considered poor form. Style 4 -- Bad: This syntax follows terrible form, and may cause some tags to malfunction.

52 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

21 Comment Tag Comments The word "comment" has a specific meaning in programmer-speak. A comment is a word, sentence, or group of sentences which, when embedded in a piece of code, explain something about that code, such as what it does or how it works. A comment does not itself have any effect upon a program or a web page. A comment is invisible to a user, and is meant as a note from a programmer to another programmer, or as a note to himself/herself. A comment should clarify something about the code (why has it been written the way it has been, what it does, what it is for, etc). Comments can also be used to mark significant starting and ending points in code, or for any number of other purposes. In HTML, a comment is just another tag, although it follows special rules. Here is what an HTML comment looks like in code: <!-- Here is a comment -->

A comment begins with <!-- followed by a space, and ends with a space followed by -->. The space just after the hyphens in the opening part of comment is required, as is the space preceding the hyphens in the closing portion of the comment (these spaces are required to support non-standard commenting in some versions of Internet Explorer). In addition, a comment must not contain any carriage returns in the middle of the tag if it is to support older versions of Internet Explorer; the entire comment must be made on one line. Incorrect (multiple lines): <!-- Here is a comment -->

Incorrect (missing spaces): <!--Here is a comment-->

Correct: <!-- Here is a comment --> <!-Here is a comment Here is another comment -->

Here is an example of some HTML comments in action: <!-- begin article one --> <h3>The Bandicoot</h3>

53 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<p>The bandicoot is a ferocious creature, but is now rarely seen by civilized man. <!-- Sally, please check last known bandicoot attack in China, 1952? 1953? --> In the seventh century BC, the bandicoot was considered to be the greatest threat to man's survival since the saber-toothed tiger, but, due to an epidemic of bandicoot coot-pox in the 1st century AD, <!-- Sally, could you check dates on epidemic, please? --> was almost entirely wiped out.</p> <!-- end article one -->

Note how I have marked the beginning and ending points of "article one" above with comments; I've done this so that other people will be able quickly to figure out where to replace articles on the page. This sort of beginning/ending marker is probably the most common type of comment found in professional HTML code. I have also added additional comments into the article text for editorial purposes, asking my mythical assistant, Sally, to run some factual checks for me. Comments may be used for any purpose. Whenever you wish to place a note, a reminder, or a piece of information into HTML code that's invisible to a user and does not affect the HTML code, you may use a comment. Comments are particularly valuable when creating tables in HTML, helping to mark main content areas within a large and oftentimes complex layout; we'll discuss more about commenting tables in a later module.

54 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

22 Special Characters Special Characters Certain characters in HTML are reserved, such as the less-than (<) and greater-than (>) signs, and the ampersand (&) character. If you type characters like these directly into HTML code, you will usually (although not always) get either a broken web page, or gibberish characters on the screen. In order to display reserved characters, you must use character entity references, also known as escape sequences or escape characters. The syntax for escape characters in HTML is always the same: The ampersand (&) character, followed by the character code, and ending with a semi-colon (;). The character codes may be represented either by name (named entity) or by number (numeric entity); named entities are special text abbreviations of the character name, while numeric entities are special number codes representing the character preceded by a pound (#) sign. Remember: these codes MUST start with an ampersand and end with a semi-colon. Examples: Character: < (less-than sign) Escape Character: < or < Character: > (greater-than sign) Escape Character: > or > Character: Š (copyright symbol) Escape Character: © or © Character: & (ampersand) Escape Character: & or & Note: Firefox will sometimes display an apostrophe or quotes as hex characters ? or as a ? The reason is that the user has used a curly apostrophe or quotes (probably copied and pasted from a doc file) You can fix this by replacing the curly apostrophe or quotes with the proper character from your keyboard. Alternatively: Replace the curly apostrophe with ' Replace the curly quotes with " For full special character list, see: http://www.utexas.edu/learn/html/spchar.html

55 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Another invalid character that will show ? involves an accent over a character. for ex: É (use É) For full accent list, see http://www.tlt.psu.edu/suggestions/international/web/codehtml.html#accent

56 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

23 PRE Tag PRE Tag Tag: PRE Description: Used to set pre-formatted text. Always closes. The PRE tag always displays content using the browser-default monospace font (usually Courier 10pt). BR tags are not required for line breaks within the PRE tag; ordinary carriage returns are recognized as line breaks, making the BR tag unnecessary. The PRE tag also respects space characters, displaying all spaces individually, rather than compressing a group of spaces together and displaying them as a single space. Example: <pre> Shoo, Shoo, Shoemaker By Ogden Nash I often grieve for Uncle Hannibal Who inadvertently became a cannibal. He asked Aunt Mary to roast him the gobbler; She understood him to say, the cobbler. </pre>

Displayed: Shoo, Shoo, Shoemaker By Ogden Nash I often grieve for Uncle Hannibal Who inadvertently became a cannibal. He asked Aunt Mary to roast him the gobbler; She understood him to say, the cobbler.

The PRE tag is also useful for displaying multiple-line code fragments, as it preserves spaces and carriage returns that would ordinarily be ignored. Example: <pre> Now is the time for all good people to come to their senses </pre>

Displayed: Now is the time for all good people to come to their senses

57 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

The PRE tag can also be used to create space between elements on an HTML page; every carriage return placed between the <PRE></PRE> is displayed in the browser. This is an officially supported alternative to the more common (but non-standards-compliant) practice of placing multiple BR tags on a page in order to create visible white space. Example (non-standard/unofficial -- avoid this): <p>Here is a paragraph of text.</p> <br> <br> <br> <p>Here is another paragraph of text.</p>

Displayed: Here is a paragraph of text.

Here is another paragraph of text. Example (supported/standards-compliant -- use this): <p>Here is a paragraph of text.</p> <pre> </pre> <p>Here is another paragraph of text.</p>

Displayed: Here is a paragraph of text.

Here is another paragraph of text.

58 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

24 Physical Style Tags and Content-Based Style Tags Physical Style Tags and Content-Based (or Logical) Style Tags There are a group of tags, used to mark-up text styles, which split into two types: physical and content-based style tags. Physical style tags include B (bold), I (italic), SUP (superscript), SUB (subscript), and many more; these tags act physically on text exactly as they claim. Content-based style tags include STRONG (strong), EM (emphasis), CITE (cite/citation), etc; these tags represent what something MEANS, rather than what something looks like. Whereas physical style tags impart a specific appearance to text that they mark-up, content-based style tags impart information regarding what that text is supposed to BE, or what it is used for. The fact that content-based style tags impart appearance characteristics to text is completely secondary. All of these tags are used to mark text, usually within a paragraph, but occasionally on their own. They ALL must close.

Physical Style Tags Physical style tags are quite straightforward; they do exactly what they claim. B, I, SUP, SUB, and TT are fairly common. BIG and SMALL are rarely used, as they may not operate correctly in Netscape 4.x browsers. Here is the list of physical style tags, seen in action: Tag: B Description: Makes text bold. Example: <p>Hi there, <b>bold</b> boy.</p> Displayed: Hi there, bold boy. Tag: I Description: Makes text italic. Example: <p>Slant <i>this way,</i> my little flower.</p> 59 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Displayed: Slant this way, my little flower. Tag: SUP Description: Makes text superscript. Example: <p>Einstein Says: E = Mc<sup>2</sup></p> Displayed: Einstein Says: E = Mc2 Tag: SUB Description: Makes text subscript. Example: <p>The chemical formula for Sulfuric Acid is H<sub>2</sub>SO<sub>4</sub></p> Displayed: The chemical formula for Sulfuric Acid is H2SO4 Tag: TT Description: Makes text "teletype", aka the default monospace font (ordinarily, Courier 10pt, but this is dependant entirely on the user's browser settings). Example: <p>Mr. CodeHead says: <tt>var myGoober = 10 * myRadius;</tt></p> Displayed: Mr. CodeHead says: var myGoober = 10 * myRadius; Less Common Physical Styles: Tag: BIG Description: Makes text bigger. Example: <p>See how much <big>bigger</big> I am?</p> Displayed:

60 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

See how much bigger I am? Tag: SMALL Description: Makes text smaller. Example: <p>This text is much <small>smaller</small> than anything else.</p> Displayed: This text is much smaller than anything else.

Content-Based Style Tags Content-based style tags are more concerned with what a particular piece of text means or represents, rather than what it looks like. Content-based style tags are probably going to disappear, over time, in favor of custom XML tags; XML tags are much more flexible and expansible in terms of the content they can potentially mark up. Of the content-based tags, only three are in occasional use today: EM (emphasis), STRONG (strong), and CITE (cite/citation). Tag: EM Description: Adds emphasis to a piece of text, usually rendered using italics. Example: <p>I <em>really</em> want to do something with my life.</p>

Displayed: I really want to do something with my life. Tag: STRONG Description: Makes text stronger, very emphatic; is usually rendered in bold text. Example: <p>I <em>really</em> want to do <strong>something</strong> with my life.</p> Displayed: I really want to do something with my life. Tag: CITE Description: Marks a citation (indicated in italics), giving credit to a work or author. The CITE tag is supposed to mark a citation for a book, magazine, or article title, and may 61 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

include an A (anchor) tag surrounding the CITE, linking to that particular resource (if it is located online). Example (without anchor): <p>I love <cite>Pride and Prejudice</cite>, by Jane Austen.</p>

Displayed: I love Pride and Prejudice, by Jane Austen. Example (with anchor): <p>I love <a href="http://www.pemberley.com/janeinfo/pridprej.html"><cite>Pride and Prejudice</cite></a>, by Jane Austen.</p> Displayed: I love Pride and Prejudice, by Jane Austen. Theoretically, instances of a CITE tag within a document could be extracted to create a bibliography of works from your web site, including links; this task could be performed by a web browser automatically, were this feature ever implemented by anybody (which it hasn't been). Another use of the CITE tag is a modification of its true purpose, marking a creator of a particular web page, and/or the date when that page was last updated. Warning: the CITE tag does NOT put a special line break or carriage return preceding or following itself, so you'll need to watch your formatting carefully. Example: <cite> Creator: Steve Rubin<br> Last Updated: October 31, 2006 </cite>

Displayed: Creator: Steve Rubin Last Updated: October 31, 2006 If you want to give an address on a web page in place of or in addition to your citation, use the ADDRESS tag (this is not a content-based style, but I think I should mention it anyway). Tag: ADDRESS Description: Marks a mailing address, including email contact, if applicable. <address> <a href="mailto:webmaster@blug.com">Webmaster</a><br>

62 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

1234 Main St.<br> Brickbath, MI<br> </address>

Displayed: Webmaster 1234 Main St. Brickbath, MI

63 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

25 BLOCKQUOTE and HR BLOCKQUOTE and HR Fashions in HTML programming come and go almost as quickly as fashions in clothing. Two useful tags which have waxed and waned in fashion several times are BLOCKQUOTE and HR. BLOCKQUOTE is used to set off a block of quotation. HR (Horizontal Rule) is used to create a dividing line across an HTML page. Tag: BLOCKQUOTE Description: Set off a quotation from other text. Similar to P (paragraph), except that it indents text automatically. Example: <blockquote> "But, soft! What light through yonder window breaks?<br> It is the east, and Juliet is the sun!"<br> -- <cite>William Shakespeare</cite> </blockquote>

Displayed Example: <blockquote><blockquote> This is my first homepage. It will improve in time, if I'm lucky. Please don't laugh too hard at the simplicity of this page. I like to go skydiving in my spare time. Barack Obama is the best president ever. I am a student at City College of San Francisco and my instructor is Steve Rubin. </blockquote></blockquote>

Displayed Tag: HR Description: Inserts a dividing line, or horizontal rule, across an HTML page. Its appearance may be modified using selected attributes. Example (inserted between two paragraphs of text): <p>Here is a paragraph of text.</p> <hr> <p>Here is another paragraph of text.</p>

Displayed: Here is a paragraph of text.

64 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Here is another paragraph of text. Tag: HR Attribute: SIZE Value: integer representing thickness of horizontal rule in pixels Description: sets HR thickness. Example: <hr size="5">

Displayed: Tag: HR Attribute: WIDTH Value: integer representing width of horizontal rule, in pixels. May also be set to percentage value (representing percentage of browser window width). Description: sets HR width. Example: <p>Paragraph of text.</p> <hr width="300"> <p>Paragraph of more text.</p> <hr width="50%"> <p>Final paragraph of text.</p>

Displayed: Paragraph of text. Paragraph of more text. Final paragraph of text. Tag: HR Attribute: ALIGN Value: left, right, center Description: sets the alignment of a horizontal rule on a page. Example:

65 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<hr width="200" align="left">

Displayed: Horizontal rules are usually inserted to indicate section breaks in a long document, or as a divider or decorative element. HR tags used to be used with such frequency that they came to be associated with unimaginative web page design, and should be used sparingly.

66 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

26 Miscellaneous HTML Tags Miscellaneous HTML Tags Tag: BR Attribute: CLEAR Values: all, left, right Description: The BR tag, in combination with an IMG tag, can define how text will break in relation to a left-or-right-aligned image. clear="all" forces text to break below all images; clear="left" forces text to break below the left-aligned images; clear="right" forces text to break below the right-aligned images. "all" is the only commonly used value for the CLEAR attribute. Example: <br clear="all"> When used in combination with left or right aligned images, the BR tag can determine how and when text (or other images) will wrap in relation to the image. The BR tag with the CLEAR attribute is useful when laying out images and text together (or images and other images). Try it for yourself! Tag: NOBR Description: Marks words which may not break, even if that means that they go off the edge of the screen. Very useful for holding together specialty phrases or sets of words which must appear together in a paragraph, or for holding a set of images together on one line. Always closes. Tag: TT, CODE Description: TT is a physical style tag, while CODE is a content-based style tag. They both work identically, causing marked content to display using the browser's default monospace font setting (usually Courier or Courier New 10 point text). Both tags MUST close. Unlike PRE, which always sets its content off from surrounding content (as well as preserving spaces and carriage returns, which TT and CODE do not), TT and CODE may be used within the flow of ordinary HTML paragraphs. Example: <p>I like to think about my <tt>HEAD</tt> and my <tt>BODY</tt> when I exercise my <tt>HTML</tt>. <tt>var fred = 1;</tt> is a nice piece of JavaScript code.</p> Displayed: I like to think about my HEAD and my BODY when I exercise my HTML. var fred = 1; is a nice piece of JavaScript code.

67 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Example: <p>I like to think about my <code>HEAD</code> and my <code>BODY</code>when I exercise my <code>HTML</code>. <code>var fred = 1;</code> is a nice piece of JavaScript code.</p> Displayed: I like to think about my HEAD and my BODY when I exercise my HTML. var fred = 1; is a nice piece of JavaScript code.

68 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

27 META Tag The META Tag The META tag is used primarily for two purposes today: 1. It helps robotic search engines (such as Google and Yahoo) better categorize your HTML pages. 2. It automatically moves users from one page to another (as seen on splash pages or forwarding-address pages) using its auto-refresh capabilities. The META tag requires two attributes: NAME and CONTENT. NAME identifies the type or variety of META tag in question; CONTENT sets the necessary information for that version of the META tag. The NAME attribute, in some cases, is interchangeable with the HTTP-EQUIV attribute; in other words, either NAME or HTTP-EQUIV will be used as the identifier attribute for the META tag, depending on the purpose of that particular META tag; the second attribute will always be CONTENT. The META tag does not need to close in HTML4. The META tag always goes within the HEAD of an HTML page; it is NEVER placed in the BODY. You may place as many different META tags in the HEAD as you like. Examples (out of context): <meta name="keywords" content="Steve Rubin, web design, html, critical thinking"> <meta name="description" content="Home Page of Steve Rubin, CNIT Instructor at CCSF."> <meta http-equiv="refresh" content="10; url=http://www.yahoo.com/

Examples (in context): <html> <head> <title>Example META tags</title> <meta name="keywords" content="Steve Rubin, web design, html, critical thinking"> <meta name="description" content="Home Page of Steve Rubin, CNIT Instructor at CCSF."> <meta http-equiv="refresh" content="10; url=http://www.yahoo.com/"> </head> <body> <p>Some content...</p> </body> </html>

Keywords and Description Feature

69 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

<meta name="keywords" content="Steve Rubin, web design, html, critical thinking"> <meta name="description" content="Home Page of Steve Rubin, CNIT Instructor at CCSF.">

An HTML page on the Web is catalogued in a search engine's database with one entry for every pertinent keyword on the page. Each individual word in the TITLE of an HTML document receives a separate keyword entry in the database. Each individual keyword in the KEYWORDS META tag receives a separate keyword entry in the database. In some cases, each single word in the text of an HTML page receives an individual keyword entry in the search engine's database, as well. Again, these entries are prioritized based (in order of importance) on 1. whether the word is in the TITLE (top priority), 2. whether the word is in the KEYWORDS META tag, and 3. whether the word appears in the text in the BODY of the HTML page. In addition to the position of the keyword on the HTML page as a whole, the search engine "grades" the importance of a given HTML page based on how close that page is located to the root directory of its domain; top level (root directory) pages are given top priority, even if a given keyword does not appear in the TITLE of that document, but merely in the META tag or in the BODY. Many search engines also recognize the DESCRIPTION META tag. The DESCRIPTION META tag allows you to create a brief description of your page or website which will display below the TITLE and URL for your website on a robotic search engine's results page. In other words, when a user performs a keyword search at AltaVista, he/she receives a number of results pages which contain links to various web pages; these links are usually represented by the TITLE of the HTML page in question, the text of that TITLE having been hyperreferenced to the desired page; the URL of the page is also present. Right below this information, there is a brief text description of the page. If the DESCRIPTION META tag has been set for that page, then the user sees the CONTENT of the DESCRIPTION META tag. If the DESCRIPTION META tag has NOT been set, then the user sees the first 10-20 words from the BODY of that HTML page in place of the description.

Auto-Refresh Feature <meta http-equiv="refresh" content="10; url=http://www.yahoo.com/">

Two attributes of the META tag are required to utilize the auto-refresh feature: HTTP-EQUIV and CONTENT. The HTTP-EQUIV attribute must be set equal to "refresh". The CONTENT attribute must be set equal to a value following this format: "secondsOfDelay; url=someURL" The value of the CONTENT attribute is broken into two segments, separated by a semi-colon. The first segment is an integer representing the number of seconds of delay you want once the

70 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

HTML page which contains the META tag has been loaded. The second segment is url= followed by the absolute or relative URL desired.

71 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

28 Document Appearance Document Appearance Each web browser (whether Internet Explorer or Firefox) has preferences which may be set by the user to control default appearance for HTML pages. The original default browser preferences (preferences preset by the manufacturer) used to be somewhat consistent crossbrowser and cross-platform, but this consistency has begun to decay in recent years. Generally, however, default browser appearance settings are as follows: Light Gray page background color (or White) Black text Blue Link color Purple Visited Link color Red Active Link color (the color the link turns while being clicked) Links are underlined Proportional Font: Times or Times New Roman, 12pt. Monospace Font: Courier or Courier New, 10pt. If no appearance information is set in the code for an HTML page, the browser default preferences will apply to that HTML page. As I mentioned earlier, web browser default settings have begun to deviate from the traditional standards stated above. Some browsers are attempting to correct for differences between Mac and PC font-sizes automatically, which was supposed to make our lives easier, but instead made creating consistent-looking, cross-platform, backward-compatible, general-purpose, professional-quality HTML pages WITHOUT CSS almost impossible. Because of changes to the web browsers, and because users can change their web browser default settings to suit their every whim anyway, it is more important than ever to learn to control HTML tag appearance using CSS if you want to achieve true consistency of HTML appearance. We will discuss CSS, in brief, in a later module. What is the difference between the Proportional and Monospace Fonts? Proportional fonts, such as Times, Times New Roman, Arial, and Helvetica, use different sized spaces for the width of each letter. An "i", for instance, isn't as wide as an "M", and a space character may be of several different sizes. Proportional fonts are used for laying out most ordinary body text, whether for publishing on the Web or for print purposes. Most text within the BODY of an HTML document is laid out using the browser's default proportional font. Monospace fonts, such as Courier and Courier New, have characters which are all identical in width. A space character is as wide as an "M", which is as wide as an "i"; all characters in a monospace font are the same width. This characteristic of monospace fonts makes them ideal 72 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

for use in programming, where all code is written in text-only documents with no formatting, where space-character indenting is common. Web browsers use the default monospace font setting to display text which lies within the CODE, TT, or PRE tags (among others). The default font SIZES for an HTML page are particularly tricky. Macintosh and Windows PC machines will display 12 point text in a browser window at different sizes (PC fonts display substantially larger in a web browser window than Macintosh fonts, even if both platforms are using the exact same font). It is impossible to create HTML pages which display with identical font sizes cross-platform without the use of CSS. Without CSS, in fact, it is impossible to be certain of the font size under any circumstances, since users may reset browser default font sizes at will. When designing pages for the Web, you will do so with default browser fonts in mind, but your designs must be flexible. By the end of this class, you will have received a basic introduction to Cascading Style Sheet technology (CSS). When working professionally, however, you are likely to encounter older HTML means for controlling document appearance, using tags and attributes which have been deprecated (retired). We'll talk about CSS in a later module; we'll talk about these deprecated tags and attributes now. Tag: BODY Attribute: BGCOLOR Value: any named color or hexadecimal color code Description: Use BGCOLOR to set the background color for an HTML page. Example: <body bgcolor="#FFFFFF"> Tag: BODY Attribute: BACKGROUND Value: a URL (relative or absolute) for a GIF or JPEG file Description: Sets the background image for an entire HTML page. This image will tile (repeat horizontally and vertically to fill the entire browser window), so make certain that your image is appropriate for tiling. Background images should not be more than 10K in file size; some browsers will not display foreground content until the entire background image has been downloaded. Tag: BODY Attribute: TEXT Value: any named color or hexadecimal color code Description: Use TEXT to set the primary text color for an HTML page. Example: <body text="#000000"> Tag: BODY Attribute: LINK Value: any named color or hexadecimal color code Description: use LINK to set the color for unvisited hyper-links.

73 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Example: <body link="#0000FF"> Tag: BODY Attribute: VLINK Value: any named color or hexadecimal color code Description: use VLINK to set the color for visited hyper-links. Example: <body vlink="#FF00FF"> Tag: BODY Attribute: ALINK Value: any named color or hexadecimal color code Description: use ALINK to set the color for active hyper-links (links currently being clicked on) Example: <body alink="#FF0000"> Example HTML page using all of these properties: <html> <head> <title>Silly Demo Page</title> </head> <body bgcolor="#FFFFFF" background="./graphics/bgrdLeaves.gif" text="#000000" link="#0000FF" vlink="#FF00FF" alink="#FF0000"> <p>Some content... Here's a <a href="#">hyper-reference</a>.</p> </body> </html>

Note: You may set both the BGCOLOR and the BACKGROUND attributes for the BODY tag; as the background image is loading, the foreground content will be displayed on a background the color of BGCOLOR. Remember: all of the above attributes have been replaced by CSS properties. They are still legal to use, however. Before CSS, there was the FONT tag, which allowed HTML programmers to set a font's color, size, and face (the FACE attribute sets the name of the font that you wish to use). The FONT tag should NOT be used; it has been completely replaced with CSS. However, it is important that you understand the FONT tag well enough to review older work. Tag: FONT (always closes) Attribute: COLOR Value: any named color or hexadecimal color code Description: Use the COLOR attribute of the FONT tag to set the color of text which appears between the opening and closing FONT tags. Example: <font color="#FFFF00">Howdy There.</font>

74 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

Tag: FONT Attribute: SIZE Value: integers from 1-8; 1 is smallest, 8 is largest. May also indicate relative sizes by using + and - signs before integers, i.e. "+1", or "-2". The default font size is always 3; therefore, if you say size="+1", it usually means that your font size is 4. Font sizes 1-8 are in relation to the web browsers' default proportional font, which is usually Times 12pt; whatever size is set as the browser's default proportional font, however, will count as size="3". Description: Set the relative size of text inside a FONT tag using the SIZE attribute. This is not a very accurate means of setting font size, but it was all that was available prior to the advent of CSS. If you're designing on the PC, remember never to use size="1", as that is usually unreadable on the Macintosh. Example: <font size="5">Larger Text</font>

Tag: FONT Attribute: FACE Value: Font names. Multiple font names may be used, separated by commas. Always end with one of the five default font names: serif, sans-serif, monospace, cursive, or fantasy. Description: Allows you to set a different font than the browser defaults, assuming that the user has that font loaded into their system. Always use standard system fonts for PC and Macintosh. The first choice font should come first, then the second and third choice fonts. Remember: PCs and Macs have different sets of base fonts, so use at least one PC font name and one Mac font name. Example: <font face="Arial, Helvetica, sans-serif">Text</font>

Note: Pages destined for printing should NOT use the FONT tag with the FACE attribute. Each time the FONT tag appears on a page with the FACE attribute, some web browsers download a copy of that font to the printer, whether or not it has already been downloaded. Thus, if you state "Verdana" as your chosen font 15 times on the page, the web browser will load "Verdana" fifteen times into the printer; this will cause some printers to crash. More than one attribute may be set for the FONT tag, of course. Example: <font face="Courier, Courier New, monospace" size="5" color="#660000"> Blah Blah Blah. </font>

Again, don't use FONT tags in combination with CSS; they are not designed for use together. You may experiment with the FONT tag, if you wish. However, don't get in the habit of using it; CSS is a far superior alternative. Even with CSS's bugs and inconsistencies, CSS does

75 of 76

8/16/10 2:41 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136069

everything the FONT tag does, and more, with greater precision and reliability. Screen resolution: I will be viewing your webpages with a screen resolution of 1024X768. Since this is the most common screen resolution for most people, I suggest you also use it.

76 of 76

8/16/10 2:41 PM


name

10/24/10 7:17 PM

Book 2: XHTML and Tables Book for Weeks 3-4:

XHTML and Tables

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 2: XHTML and Tables Printed by: Donald Siino Date: Sunday, 24 October 2010, 07:17 PM

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 1 of 40


name

10/24/10 7:17 PM

Table of Contents 1 XHTML Overview 2 XHTML Elements and Rules 3 Important Notes about XHTML Validation 4 Introduction to Tables 5 Basic Table Construction 6 COLSPAN and ROWSPAN 7 ALIGN and VALIGN 8 Table Miscellaneous: CELLSPACING, CELLPADDING, etc. 9 Fixed Width Tables 10 Variable Width Tables 11 Video Tutorial - XHTML Validation

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 2 of 40


name

10/24/10 7:17 PM

Reference in Musicano Book: Ch. 16

XHTML Overview By the late 1990's, the W3C (World wide Web Consortium) was interested in standardizing what was called version 4 of HTML. But Explorer and Navigator often played fast and loose with the official version, each in their own way. And the problem of complexity remained. For browsers designed to run on personal computer, this looseness and complexity does not pose a major problem. PCs have plenty of memory and storage space. Everyone could see, however, that a new generation of webenabled devices like hand-held computers and intelligent cell phones was on the way. The W3C estimated that by 2002 up to 75 percent of computers connected to the Internet would be small webenabled devices. Like many predictions, their timing was overly optimistic, although clearly the trend is in that direction. Such devices do not have the memory and storage space to handle a full-featured browser displaying full-featured web pages. Nor would most web pages, which are designed to be viewed on PC monitors, display well on the screens of small devices. In addition, there was the problem of HTML not being able to handle nontraditional content such as chemical formulae, musical notation, or mathematical expressions. To answers these needs, the W3C decided that instead of making an HTML version 5, it would turn to a different language that it had been developing: Extensible Markup Language, or XML. The primary motivation for creating XML was the need to send data over the Internet in a universal, structured format, especially as electronic commerce and data exchange over the Internet began to take off in the 1990's. XML is a set of rules that lets web designers classify their data in a way customized to their needs by creating new types of tags. Thus the name extensible: XML allows designers to extend the language to fit their needs. The W3C decided that the best approach to solve HTML's problems would be to reorganize and reformulate it from the ground up using XML rules. Because this new version of HTML would not be based on earlier versions of HTML, but on XML, it was named Extensible Hypertext Markup Language, or XHTML. The first version of XHTML was released in january 2000. Navigator 6 and Explorer 6 both support XML for the most part, and thus also support XHTML. In order to ensure that XML is universal, (that it works no matter the device being used), it has has some very strict rules. As an XML-based language, XHTML inherits these rules (and their benefits). For example, unlike HTML, XHTML is a case-sensitive language. The way you type the name of an element matters. The W3C chose to use lowercase letters for XHTML tags. So, even though <BODY> or <body> is acceptable in HTML, only <body> would be correct in XHTML. Two other important rules for using XHTML: all tags must have corresponding ending tags and all tags must be properly nested. Now let us look in more detail at what you will need to create an XHTML document. NOTE: When using XHTML to create a Web document, your file extension should be html, NOT xhtml. For example, hw2.html is correct, whereas hw2.xhtml is NOT correct.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 3 of 40


name

10/24/10 7:17 PM

XHTML Elements and Rules At the very beginning of an XHTML document, you should place the following: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> The first line is an XML declaration that indicates to the browser the version of XML used for the document's code; that is, it is an XML document that uses custom tags as defined by the W3C's XHTML specification along with the 8-bit Unicode character set, the one most commonly used today. If a browser is going to be able to recognize and correctly display the tags contained in the document, it needs to know about the XHTML specification. The second and third lines in the code above give this information to the browser. These lines (which may be written all on one line) make up what is called a Document Type Definition (DTD). As the name implies, the DTD specifies what type of document this is (in this case an XHTML document). The DOCTYPE declaration lets designers specify the DTD file that has the definitions of all the tags and attributes used within the XHTML document. The next line in the code involves the <html> tag. It becomes: <html xmlns="http://www.w3.org/1999/xhtml"> The xmlns stands for XML namespace, which helps the browser keep track of what all the custom XML tags mean, especially if the same name is used for different tags. A namespace lessens the confusion by providing the browser with information on the meaning of the tags in the document. By adding the above xmlns information to the <html> tag, we are telling the browser that all tags contained within the <html> element belong to the XHTML namespace, as defined by the W3C and located at the given URL. It should be noted that our textbook gives the namespace as: <html xmlns="http://www.w3.org/TR/xhtml1"> The validation services do not currently accept this as a valid namespace. At this point, you might ask the question: "What about the millions of existing web pages that follow the old rules? Will they suddenly cease to work?" Because there is such a large installed base of web pages created under the old rules of HTML version 4 and before, it is likely that the major PC browsers will continue to recognize old HTML code and display it properly. But as browsers are designed for other new devices, it's likely that only XHTML-based web pages will work on them. Many web designers are already using XHTML rules for their new web pages and rewriting their previous web pages to be compatible with XHTML. Fortunately the gap between XHTML and HTML is not that great. I must confess though that because of time constraints, many of the web pages and examples given in the course content modules are in done HTML4, NOT in XHTML. For the remainder of your XHTML document, as long as you adhere to the following rules, you'll be writing proper XHTML: XHTML documents must be well-formed XHTML documents must have a <title> element within the header section Elements must nest and not overlap http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 4 of 40


name

10/24/10 7:17 PM

All element and attribute names must be in lowercase All tags must close All attributes must have values enclosed within quotes

XHTML documents must be well-formed: With the exception of a frameset page, a well-formed XHTML document has an <html> root element that contains two embedded, non-overlapping sections, namely "head" and "body". So, the shell of an XHTML document would look like this (with .... referring to the content of each section): <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> .... .... </head> <body> .... .... </body> </html>

XHTML documents must have a <title> element within the header section: The <title> element has been around since HTML 2.0, and although recommended for any web page, it is not required by the browser. If omitted, the viewer will see 'untitled' in the browser's title bar. In XHTML, the <title> element is required. For example: <head> <title>Steve Rubin's Homepage</title> </head>

Elements must nest and not overlap: Most web browsers don't care if you overlap elements by writing code such as the following, in which the <i> tag starts within a paragraph element and ends outside it: <p>The following word is written in italics: <i>italics</p></i> Technically, overlapping tags are illegal (albeit widely tolerated by web browsers) in HTML as well. However, as mentioned previously, XHTML documents must be well-formed. One day soon Web browsers will enforce the XHTML standard and will not "guess" what is meant when the XHTML statement syntax is wrong. If you always write your closing element (and section) tags in reverse of the order in which you wrote the opening tags, your elements (and sections) will not overlap. The following is correct:

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 5 of 40


name

10/24/10 7:17 PM

<p>The following word is written in italics: <i>italics</i></p>

All element and attribute names must be in lowercase: HTML, unlike XHTML, is case insensitive. For example <BODY> is the same as <body> within an HTML document. As a result, many authors try to make the code within their web page files more readable by writing element names in all capital letters to set HTML tags off from text content and attributes (written in lowercase). For example, the following would be correct using HTML: <BODY BGCOLOR="yellow"> <P>This is a paragraph</P> Although easy to pick out, none of the above tags are valid in XHTML. Because XHTML is casesensitive and the XHTML DTD contains elements in lowercase, you must write XHTML tags in lowercase. Otherwise, the browser will ignore the undefined tag. The following would be correct using XHTML: <body bgcolor="yellow"> <p>This is a paragraph</p> In XHTML, although you must write attribute names in lowercase, you can write attribute values in either upper or lowercase. For example, the following is valid in XHTML, even though I don't recommend it. <body bgcolor="YELLOW">

All tags must close: Many authors have used the <p> tag to separate paragraphs when using HTML. The <p> tag essentially inserts a blank line and moves to the left margin. For example: This is the first paragraph<p> This is the second paragraph<p> This is the third paragraph This practice is NOT valid in XHTML. You must close each paragraph container that you open with a <p> tag. The following would be correct in XHTML. <p>This is the first paragraph</p> <p>This is the second paragraph</p> <p>This is the third paragraph</p> In fact all container tags, such as the <p> tag must have a corresponding closing tag, such as </p>. This is true for all container tags, such as list (<ul></ul>), list item (<li></li>), table (<table></table>), etc. In HTML, it is possible and more syntactically correct to replace the <p> tag with the <br> tag. For example: This is the first paragraph<br><br> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 6 of 40


name

10/24/10 7:17 PM

This is the second paragraph<br><br> This is the third paragraph In XHTML, you must terminate empty tags such as the <br> tag with a space followed by a forward slash ("/"). For Example: <br /> This requirement to close empty tags also extends to all other tags, which would not normally close in HTML. For example: <img src="xyz.gif" /> <meta name="keywords" content="Steve Rubin, web design, critical thinking" /> <bgsound="xyz.wav" />

All attributes must have values enclosed within quotes: You will find plenty of tags within HTML documents where the author assigned numeric (and sometimes single-word text) values to attributes without enclosing the value in quotes. For example: <body bgcolor=blue> <img src=xyz.gif width=200 height=300> <map name=europe> All of the above would be incorrect in XHTML. XHTML requires that all attribute values (both numeric and text) be enclosed within quotes. For Example: <body bgcolor="blue"> <img src="xyz.gif" width="200" height="300" /> <map name="europe"> In addition, XHTML requires that all attributes have a value. HTML lets you use a shortcut called attribute minimization when using an attribute that can have only one possible value. When allowed, attribute minimization lets you omit the attribute's value and specify only its name within the HTML tag. For example, the following is correct in HTML: <input type="checkbox" name="choice" value="europe" checked> The above example is incorrect in XHTML. In XHTML, it would be correctly coded as follows: <input type="checkbox" name="choice" value="europe" checked="checked" /> Thus, in XHTML, we are required to state each attribute's value explicitly (and within quotes), even when only one value is possible.

Summary: To repeat, when I talk about HTML in this course, I mean HTML version 4, which is the current version of the HTML language. XHTML is the newest version of HTML, essentially, HTML version 5. XHTML stands for Extensible Hypertext Markup Language. XHTML has much stricter syntax than HTML4, but is otherwise virtually identical. http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 7 of 40


name

10/24/10 7:17 PM

NOTE: Feel free to use either HTML or XHTML in your Homework Assignment Web Pages, but I encourage you to only use XHTML in most of your Homework Assignment Web Pages, if not in all of them. NOTE: The examples presented from this point on in the course content modules will reflect XHTML. A full discussion of XHTML is given in our textbook in Chapter 16. View an excellent tutorial on XHTML. Take a review quiz on XHTML. You can convert your HTML code to XHTML or correct your XHTML code, using this W3C service, called tidy. Before using tidy, I suggest inserting at the top of your HTML file the following: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> You should validate your XHTML code at http://validator.w3.org/. To check whether you have broken links (especially non-clickable links), go to Link Checker from W3C. Check here for CSS Validator.

Strict XHTML: For this course, I recommend using a a transitional XHTML DOCTYPE. If you want the most rigorous XHTML validation then you should use a strict XHTML DOCTYPE by using the following: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

HTML5: HTML5 is currently under development as the next major revision of the HTML standard. Like its immediate predecessors, HTML 4.01 and XHTML 1.1, HTML5 is a standard for structuring and presenting content on the World Wide Web. The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears. According to the W3C timetable, it is estimated that HTML5 will reach W3C Recommendation by late 2010. Here is a preview of HTML 5 by Lachlan Hunt.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 8 of 40


name

10/24/10 7:17 PM

Important Notes about XHTML Validation A. Why Validation Is Important: The Main Reasons are: 1. Validation helps to ensure your web page looks right, no matter what web browser is being used. 2. Search engines can view and understand the page content. Some errors may prevent your content from being read by the search engines. 3. Pages are more accessible to people with disabilities. For a thorough explanation of the reasons, visit W3C's Why Validate? page. Common Errors and Their Fixes: 1. Required attribute "ALT" not specified. To make pages usable for people with images turned off and the sight-impaired (who may be using screen-reader software), you can set a bit of text to display in place of or describe each image. The search engines like this text, too, because it gives your pictures meaning. These errors are easily fixed by setting the appropriate text for each picture. 2. Cannot generate system identifier for general entity "XXXX" or Found '&' within 'href'. You should use '&' instead of just plain ampersands within web page links. 3. No document type declaration; implying "<!DOCTYPE HTML SYSTEM>". 4. There is no attribute "XXXXX". An attribute is something you add to a tag to change its look or behavior. This error happens when you try to use an attribute that isn't allowed for a particular type of tag, and is usually solved by using CSS to make the setting. For example, the attribute, bordercolor, should NOT be used within a table tag for XHTML. Instead you should use CSS. 5. Required attribute "TYPE" not specified. These errors usually happen when a file is "pulled in" for use on a web page. The most common types are style sheet files, and Javascript files (web page programming to do stuff like make sure you entered data into a form correctly, or to calculate a mortgage payment). This error is easily fixed by specifying what kind of file is being used. 6. End tag for element "XX" which is not open. These errors are due to sloppy editing, usually. A web page uses tags to do stuff to the text in between the tags. For example, bold text looks like this - <b>bold</b> - in HTML. If the beginning or ending tag </b> is missing, that's a problem. It's fixed by inserting the missing tag so everything matches up nicely. B. Some Quirky Validation Errors: 1. An & by itself will generate a validation error message. You can fix this by using the special character of & 2. A list should be enclosed as a block element, e.g., by using the <div> tag and </div> tag. Otherwise the validator will flag the list tags as errors. 3. A form element must always include the action attribte. 4. Note that some scripts won't validate for XHTML unless you include /* <![CDATA[ */ right after the script statement and /*]]>*/ right before the closing script statement. <script type="text/javascript"> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 9 of 40


name

10/24/10 7:17 PM

/* <![CDATA[ */ // content of your Javascript goes here /*]]>*/ </script> XHTML is subject to the same syntactical rules as XML. Because of this, an XHTML processor treats the characters < and & as markup, even if they reside inside a <script> block. see: http://javascript.about.com/library/blxhtml.htm C. Important Notes about the Validation Process: 1. For use in Firefox, I strongly suggest downloading the add-on, Web Developer for Firefox. This add-on contains a link for HTML Validation as well as CSS Validation and other useful links. 2. Some XHTML errors will cause the validator to generate several error messages. If you fix a specific error then many of the error messages may disappear. 3. Fixing validation errors usually takes a good deal of perseverance and patience. 4. After you fix validation errors on your computer then upload the new changes and click the Revalidate button for validating the new version of your page. When you finally receive the page containing the message: This document was successfully checked as XHTML 1.0 Transitional! You then copy and paste the Validation code to the bottom of your page and upload it. <p> <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-xhtml10-blue" border="0" alt="Valid XHTML 1.0 Transitional" height="31" width="88" /></a> </p> Notes: 1. You should insert border="0" to the above img statement in order to suppress the blue border. 2. You know you have a link problem, if you click on your validation icon and you get: Sorry! This document can not be checked. 500 No Host option provided

3. For validating CSS errors, you should use jigsaw. When your page passes CSS validation by receiving the message: Congratulations! No Error Found. http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 10 of 40


name

10/24/10 7:17 PM

then you can simply add in the following code to your page: <p> <a href="http://jigsaw.w3.org/css-validator/check/referer"> <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!" /> </a> </p> 4. For very difficult to fix errors, i suggest that you contact your TA.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 11 of 40


name

10/24/10 7:17 PM

Reference in Musicano Book: Ch. 10 Introduction to Tables Tables used to be the backbone of current web design. Although originally intended as a simple spreadsheet-like grid for scientific, technical, or monetary data, tables became the primary means of laying out complex, multi-column web pages. Up until quite recently, every major website used tables in some capacity for page layout. Although the introduction of CSS (Cascading Style Sheets) technology allows designers to create absolutely positioned elements on web pages, reducing the need for 100% table-based layout, the utility and backward-compatibility of tables will ensure their continued importance in web design. Tables are still an important item in the Web designer's toolbox. With the advent of mobile devices, the web page designing trend has veered away from tables and more toward a layered design using CSS. For a designer, a programmer, or a content-developer, tables will still be a part of your breadand-butter work, whether you're creating your own tables, reworking a design into a tables-suitable composition, or debugging someone else's lousy code (which usually entails rewriting the code from scratch). The principles governing table construction are fairly simple, and it is not difficult to learn the basics. Creating cross-browser, cross-platform compatible code, however, is a restrictive and occasionally frustrating experience. Most tables-based layout uses tables of mind-numbing complexity, which require special handling and careful commenting to make them functional as well as reasonable to edit and maintain. Some contemporary coding practices (including code generated by WYSIWYG editors such as Dreamweaver and GoLive) produce tables which are unstable across browsers and platforms. Here are examples of simple tables. NOTE: Technologies as CSS and XML, are making tables used as multi-column layout devices obsolete. Tables are currently reverting back to their original purpose, which is the construction of spreadsheet-like data grids.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 12 of 40


name

10/24/10 7:17 PM

Basic Table Construction As I mentioned in the introduction, tables were originally designed to create spreadsheet-like grids of scientific, technical, or monetary data. Here are a couple of simple examples: Fruits Peach

Vegetables Starches Broccoli

Bread

Apple Asparagus Potato Cantaloupe Zucchini Pasta

Escape Characters Entities Numeric Named & & & < < < Š © © Tables, as you can see, form grids of cells, each cell containing some sort of content. Tables are always defined in the HTML code using ROWS of cells, never columns; I'll show you in a minute how that works. You must carefully plan your table to ensure that you have the correct number of cells in every row, so that your table will display in even columns rather than in a big mess. Generally, tables MUST be pre-planned; you are probably not going to be able to create a decent table if you just make it up as you go along. There are four main tags associated with table construction: TABLE, TR (Table Row), TH (Table Header), and TD (Table Data). All of these tags MUST close. Tag: TABLE Description: Makes a container for a table. The TABLE tag makes a container for an entire table. All rows and cells of a given table must reside within a single pair of opening and closing TABLE tags. Tag: TR (Table Row) Description: Defines a row within a table. The TR tag creates a container for all the cells in a single row of a table. There must be one set of opening and closing TR tags for each row in a table. TR may only be declared inside the confines of a TABLE tag. Tag: TH (Table Header), TD (Table Data) Description: Defines a cell within a row of a table. Each cell in a table must be defined using either a TH or TD tag. For today's professional purposes, TH and TD are interchangeable in all respects except: TH causes its content to be BOLD text and CENTER aligned; TD causes its content to be NORMAL text and LEFT aligned. In the examples given above, cells which contain BOLD text and have CENTER alignment are marked with TH tags, while cells which contain NORMAL text and have LEFT alignment are http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 13 of 40


name

10/24/10 7:17 PM

marked with TD tags. TH tags are supposed to mark "headers" of a table, namely, the words at the top or side of a table which refer to the content of the cells in that row or column. TD tags are supposed to mark ordinary "data" in a table. Despite this differentiation, however, TH and TD tags may be used interchangeably, containing any content you desire at any position in the table; they don't have to be used for "headers" or "data" specifically. Procedure for creating tables: 1. 2. 3. 4.

Design your table; draw it on paper. In the BODY of your HTML code, lay in one set of opening and closing TABLE tags. Place one set of opening and closing TR tags inside your TABLE. Create one set of TH or TD tags for each cell in your row, placed within the opening and closing TR tags. 5. Fill in your content for the individual cells. 6. Repeat steps 3 through 6 until table is completed.

Walkthrough: I am going to create a very simple table, demonstrating all of the steps involved. Step One: Design your table; draw it on paper, if you like. Here's the design we're using for this walkthrough:

This table has two rows, with each row containing two cells. The first cell in the first row contains the number 1, and the second cell in the first row contains the number 2. The first cell in the second row contains the number 3, and the last cell in the second row contains the number 4. These numbers are just plain old typed numbers, they have no special significance; I'm using them as filler content, so that it's clear to you which cell is which. Remember that we need to lay out our HTML left-toright, then top-to-bottom, when creating our code. Step Two: Lay TABLE tag into the BODY of your HTML document. Place the pair of opening and closing TABLE tags into your HTML page. Example: <table> </table>

Step Three: Lay in your first row using TR.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 14 of 40


name

10/24/10 7:17 PM

Example: <table> <tr> </tr> </table>

Step Four: Lay your two cells into your TR using either TH or TD. For this demonstration, I'm going to use TH because it centers the text and makes it bold, which is what I wanted in my drawing. Example: <table> <tr> <th></th> <th></th> </tr> </table>

Step Five: Add the content to your first two cells. Example: <table> <tr> <th>1</th> <th>2</th> </tr> </table>

Remember: that these numbers are just ordinary text characters; the numbers have no special significance in terms of the table code. The cells must contain some content, so I'm using these numbers. Step Six: Insert the next pair of opening and closing TR tags after the first row to make your second row. Example: <table> <tr> <th>1</th> <th>2</th> </tr> <tr> </tr> </table>

Step Seven: Insert your final two TH cells into your TR. Example: http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 15 of 40


name

10/24/10 7:17 PM

<table> <tr> <th>1</th> <th>2</th> </tr> <tr> <th></th> <th></th> </tr> </table>

Step Eight: Add the content to your final two cells. Example: <table> <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th> </tr> </table>

Step Nine: Display the table in a web browser. Code: <table> <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th> </tr> </table>

Displayed: 12 34 Notice how this table has no border, and how the content is all scrunched up together. We need to add some attributes to the TABLE tag to rectify this. We'll talk about these attributes at greater length later on. In the meantime, let's set the BORDER attribute equal to "1" (which will give us a visible border) and the WIDTH attribute equal to "100" (which will make the table 100 pixels wide). Example: <table border="1" width="100"> <tr> <th>1</th> <th>2</th> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 16 of 40


name

10/24/10 7:17 PM

</tr> <tr> <th>3</th> <th>4</th> </tr> </table>

And here's what our table looks like now: 1

2

3

4

The individual cells may be a little distorted, depending on which browser we're using to view the table. If we wanted to spend the time, we could set the WIDTH attribute for each cell, which would neaten up the table somewhat. Unlike the WIDTH attribute in the TABLE tag, however, the WIDTH attribute in the individual TH and TD tags do not size cells accurately. How do you size cells accurately, then? We'll discuss that in the next module. Any kind of content could go into these cells, not just numbers. Here is the same table, with words in the four cells: <table border="1" width="100"> <tr> <th>Boo</th> <th>Baby</th> </tr> <tr> <th>Boy</th> <th>Goy</th> </tr> </table>

Displayed: Boo Boy

Baby Goy

Here's the same table, with pictures in the four cells (and the WIDTH attributeof TABLE set to 200 rather than 100): <table border="1" width="200"> <tr> <th><img src="capitalA.gif" width="54" <th><img src="capitalB.gif" width="54" </tr> <tr> <th><img src="capitalC.gif" width="54" <th><img src="capitalD.gif" width="54" </tr> </table>

height="54"></th> height="54"></th> height="54"></th> height="54"></th>

Displayed:

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 17 of 40


name

10/24/10 7:17 PM

Here's a similar table, with mixed content in the cells: <table border="1" width="200"> <tr> <th><img src="capitalA.gif" width="54" height="54"></th> <td>Boogalu!</td> </tr> <tr> <th>1025.623</th> <td> <img src="capitalD.gif" width="54" height="54"> <p>Hi There!</p> </td> </tr> </table>

Displayed: Boogalu!

1025.623 Hi There! Here's a more traditional table: <table border="1" width="200"> <tr> <th>Numbers</th> <th>Sounds</th> </tr> <tr> <td>10</td> <td>Beep</td> </tr> <tr> <td>27</td> <td>Quack</td> </tr> <tr> <td>146.17</td> <td>Oink</td> </tr> </table>

Displayed: http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 18 of 40


name

10/24/10 7:17 PM

Numbers

Sounds

10

Beep

27 146.17

Quack Oink

Here's a similar table with the same content: <table border="1" width="400"> <tr> <th>Numbers</th> <td>10</td> <td>27</td> <td>146.17</td> </tr> <tr> <th>Sounds</th> <td>Beep</td> <td>Quack</td> <td>Oink</td> </tr> </table>

Displayed: Numbers Sounds

10 Beep

27 Quack

146.17 Oink

Any number of different cell types may be placed into a single row. A single cell may contain any combination of items, from a single word, to a group of paragraphs and pictures, to another entire table! Note: XHTML does not allow for the height attribute within the table tag. If you want to validate for XHTML then you should use the height attribute in CSS.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 19 of 40


name

10/24/10 7:17 PM

COLSPAN and ROWSPAN A TH or TD cell of a table may span more than one column or row. Here's an example: <table border="1"> <tr> <th colspan="2">Weeds</th> <th colspan="2">Plants</th> </tr> <tr> <th>Pretty</th> <th>Ugly</th> <th>Pretty</th> <th>Ugly</th> </tr> <tr> <td>Queen Anne's Lace</td> <td>Crabgrass</td> <td>Rose</td> <td>Pitcher Plant</td> </tr> <tr> <td>Forget-Me-Nots</td> <td>Stinkweed</td> <td>Chrysanthemum</td> <td>Cactus</td> </tr> </table>

Displayed: Weeds Plants Pretty Ugly Pretty Ugly Queen Anne's Lace Crabgrass Rose Pitcher Plant Forget-Me-Nots Stinkweed Chrysanthemum Cactus Example: <table border="1"> <tr> <th rowspan="2">Reds</th> <td>Pink</td> <td>Magenta</td> </tr> <tr> <td>Scarlet</td> <td>Puce</td> </tr> <tr> <th rowspan="2">Blues</th> <td>Pale Blue</td> <td>Cornflower</td> </tr> <tr> <td>Turquoise</td> <td>Navy</td> </tr> </table> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 20 of 40


name

10/24/10 7:17 PM

Displayed: Reds Blues

Pink

Magenta

Scarlet

Puce

Pale Blue Cornflower Turquoise Navy

You can see that the cells denoting "Weeds" vs. "Plants" span two columns each, and that the cells denoting "Reds" vs. "Blues" span two rows each. Any TH or TD cell may span columns or rows; a given cell may, in fact, span both columns AND rows simultaneously, if desired. Here's another example: <table border="1"> <tr> <th colspan="2" rowspan="2"><img src="capitalA.gif" width="54" height="54" /></th> <td>Oof</td> <td rowspan="2">Boo</td> </tr> <tr> <td>Iddle</td> </tr> <tr> <td>Sip</td> <td>Grip</td> <td colspan="2">Rumpleteezer</td> </tr> </table>

Displayed: Oof Iddle

Boo

Sip Grip Rumpleteezer As you can see, very complex layouts become possible when cells span multiple rows or columns. A TH or TD cell may span multiple columns using the COLSPAN attribute, or multiple rows using the ROWSPAN attribute. Tag: TH, TD Attribute: COLSPAN Values: positive integers representing the number of columns to be spanned by a cell. Description: COLSPAN causes a TH or TD cell to span multiple columns of cells. Example: <td colspan="2">This cell spans two columns</td> Tag: TH, TD Attribute: ROWSPAN Values: positive integers representing the number of rows to be spanned by a cell. Description: ROWSPAN causes a TH or TD cell to span multiple rows of cells. Example: <td rowspan="2">This cell spans two rows</td>

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 21 of 40


name

10/24/10 7:17 PM

To demonstrate COLSPAN and ROWSPAN, let's create a table utilizing these two attributes. Here's what it's going to look like when we're finished: Example: <table border="1" width="500"> <tr> <th colspan="3">This cell spans <th rowspan="2">This cell spans </tr> <tr> <td>Blah</td> <td>Blooble</td> <td rowspan="2">This other cell </tr> <tr> <th colspan="2">This cell spans <th>Gobble</th> </tr> </table>

three columns</th> two rows</th>

spans two rows</td> two columns</th>

Displayed: This cell spans three columns Blah Blooble This other cell spans two This cell spans two rows columns

This cell spans two rows Gobble

In a table this complex, it may seem more difficult to figure out where a particular cell is supposed to be coded, since cells may reside in more than one row; it's really not as confusing as it looks. Remember: the row where the upper left-hand corner of a cell resides is the row into which you would code that particular cell. Always look to the upper left hand corner of a cell, and you'll never have trouble deciding into which row you need to place a particular cell. Using the BGCOLOR attribute, I have set the background color of the TH and TD cells in this revised version of the table, to make the relationships between cells and rows clearer. The cells in the first row have been colored blue, the cells in the second row have been colored red, and the cells in the third row have been colored yellow. Example: <table border="1" width="500"> <tr> <th colspan="3" bgcolor="#9999FF">This <th rowspan="2" bgcolor="#9999FF">This </tr> <tr> <td bgcolor="#FF9999">Blah</td> <td bgcolor="#FF9999">Blooble</td> <td rowspan="2" bgcolor="#FF9999">This </tr> <tr> <th colspan="2" bgcolor="#FFFF99">This <th bgcolor="#FFFF99">Gobble</th> </tr> </table>

http://insight.ccsf.edu/mod/book/print.php?id=136074

cell spans three columns</th> cell spans two rows</th>

other cell spans two rows</td> cell spans two columns</th>

Page 22 of 40


name

10/24/10 7:17 PM

Displayed: This cell spans three columns Blah Blooble This other cell spans two This cell spans two rows columns

This cell spans two rows Gobble

Tag: TH, TD Attribute: BGCOLOR Value: Any named color or hex code color Description: Sets the background color for a given cell of a table; useful for creating GIF-less designs in navigation bars, etc. Example: <th bgcolor="#CCFFCC">Stuff in Cell</th> To clarify the structure even further, I have taken a screen shot of this table, and cut it up into its essential grid structure:

As you can see, this table is REALLY built on a 4X3 grid (4 cells/columns wide, 3 rows tall), making 12 total cells. SOME of these cells, however, use COLSPAN or ROWSPAN attributes in order to take the place of their neighbor cells in the table. With this particular table, we end up with only 7 cells because of the COLSPAN and ROWSPAN attributes: 2 cells in the first row, 3 cells in the second row, and 2 cells in the third row. Now, let's create the above table, in a Step-by-Step progression; I strongly urge you to follow along, typing up this table with me. Pause the RealAudio vocal playback, as needed. Step Zero: Design the table (done) Step One: Lay in the TABLE tag Example: <table> </table>

Step Two: Lay in all the TR tags. Example: <table> <tr> </tr> <tr> </tr> <tr> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 23 of 40


name

10/24/10 7:17 PM

</tr> </table>

Step Three: Create appropriate number of cells in each row. Create the cells first; we'll fill in the content and set the necessary attributes later. Remember: You're not going to be able to review the table as you lay it out; rather, you're going to have to finish your code FIRST, then make corrections afterwards. As mentioned above, there are two cells in the first row, three cells in the second row, and two cells in the third row. As may be implied from the picture, the first row cells are all TH, the second row cells are all TD, and the third row cells are all TH. How can we tell this? Because all the text in the first and third rows is BOLD and center aligned, whereas the text in the second row is NORMAL and left aligned. Example: <table> <tr> <th></th> <th></th> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <th></th> <th></th> </tr> </table>

Step Four: Add appropriate content to cells. Example: <table> <tr> <th>This cell spans <th>This cell spans </tr> <tr> <td>Blah</td> <td>Blooble</td> <td>This other cell </tr> <tr> <th>This cell spans <th>Gobble</th> </tr> </table>

three columns</th> two rows</th>

spans two rows</td> two columns</th>

Step Five: Add necessary attributes to cells, particularly COLSPAN and ROWSPAN (where appropriate).

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 24 of 40


name

10/24/10 7:17 PM

Also add BORDER="1" and WIDTH="500" to the TABLE tag, so that the table will have visible borders and a fixed width. Example: <table border="1" width="500"> <tr> <th colspan="3">This cell spans <th rowspan="2">This cell spans </tr> <tr> <td>Blah</td> <td>Blooble</td> <td rowspan="2">This other cell </tr> <tr> <th colspan="2">This cell spans <th>Gobble</th> </tr> </table>

three columns</th> two rows</th>

spans two rows</td> two columns</th>

Step Six: The structure is finished. Now, test the table in the browser. Make corrections, if needed. Table Displayed: This cell spans three columns Blah Blooble This other cell spans two This cell spans two rows columns

This cell spans two rows Gobble

Step Seven: Add additional appearance attributes, such as BGCOLOR (if desired) Example: <table border="1" width="500"> <tr> <th colspan="3" bgcolor="#9999FF">This <th rowspan="2" bgcolor="#9999FF">This </tr> <tr> <td bgcolor="#FF9999">Blah</td> <td bgcolor="#FF9999">Blooble</td> <td rowspan="2" bgcolor="#FF9999">This </tr> <tr> <th colspan="2" bgcolor="#FFFF99">This <th bgcolor="#FFFF99">Gobble</th> </tr> </table>

cell spans three columns</th> cell spans two rows</th>

other cell spans two rows</td> cell spans two columns</th>

Displayed:

Blah

This cell spans three columns Blooble

http://insight.ccsf.edu/mod/book/print.php?id=136074

This cell spans two rows Page 25 of 40


name

10/24/10 7:17 PM

Blah Blooble This cell spans two columns

This other cell spans two rows

http://insight.ccsf.edu/mod/book/print.php?id=136074

Gobble

Page 26 of 40


name

10/24/10 7:17 PM

ALIGN and VALIGN Content inside table cells may be aligned horizontally using the ALIGN attribute, and vertically using the VALIGN attribute. ALIGN and VALIGN attributes would be used to override the default settings of the TH or TD cell tags. Tag: TH, TD Attribute: ALIGN Values: left, right, center Example:<th align="right">Something</th> The ALIGN attribute allows you to align content in a cell to the left, the right, or the center. Tag: TH, TD Attribute: VALIGN Values: top, middle (or center), bottom Example: <td valign="top">Something</td> The VALIGN attribute allows you to align content vertically in a cell at the top, middle, or bottom of the cell. Both TH and TD cells are ALWAYS valign="middle" by default. Note: The values "middle" and "center" for the VALIGN attribute have an identical effect; "middle" is the official value. Here's an Example: <table border="1" width="100" height="100"> <tr> <th align="right">1</th> <th align="left">2</th> </tr> <tr> <th valign="top">3</th> <th valign="bottom">4</th> </tr> </table>

Displayed 12 3 4 Notice how both cells in the top row automatically display their content as valign="middle" by default, since I didn't explicitly specify the VALIGN attribute in either of the cells in the top row. In the bottom row, both cells are align="center" by default because they're both created using TH tags (which automatically align center). Here's the same example, modified with additional ALIGN and VALIGN attributes; I just wanted you to understand that you can use as many of these attributes together in a tag as you wish or desire. Example: http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 27 of 40


name

10/24/10 7:17 PM

<table border="1" width="100" height="100"> <tr> <th align="right" valign="top">1</th> <th align="left" valign="bottom">2</th> </tr> <tr> <th valign="top" align="left">3</th> <th valign="bottom" align="right">4</th> </tr> </table>

Displayed 1 2 3 4 And, just so that everything is PERFECTLY clear, here is the SAME table with NO ALIGN or VALIGN attributes: <table border="1" width="100" height="100"> <tr> <th>1</th> <th>2</th> </tr> <tr> <th>3</th> <th>4</th> </tr> </table>

Displayed 1

2

3

4

The ALIGN attribute may only be added to TH or TD cells directly to control alignment inside the appropriate cells; ALIGN may not be set globally for the entire row via the TR tag if you wish to support all browsers on all platforms. VALIGN has traditionally been added to either TH or TD cells to control the vertical alignment for individual cells, or to the TR tag to control the vertical alignment for an entire row of cells; Internet Explorer 5 for the Macintosh, however, does not fully support this functionality (this is a bug). Add VALIGN to TH and TD tags ONLY, therefore, and not to TR, if you wish to support all browsers on all platforms.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 28 of 40


name

10/24/10 7:17 PM

Table Miscellaneous: BORDER, CELLPADDING, CELLSPACING, BGCOLOR, BACKGROUND, and CAPTION We've already talked about the BORDER attribute in a general way, and you know that it creates a visible border around a table. Usually we set border="1", which gives us a one pixel border. As we increase the border value, only the outside edge of the table grows; the space between the cells does not change. Large border sizes are rarely used in the professional world. Tag: TABLE Attribute: BORDER Values: integers representing number of pixels; default is 0 (no border) Description: creates border around table. Here are some actual examples: Normal one pixel border: <table border="1"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1 2 10 pixel border: <table border="10"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1 2

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 29 of 40


name

10/24/10 7:17 PM

20 pixel border: <table border="20"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1 2

To increase the amount of space in-between the cells, we must also set the CELLSPACING attribute using pixel values; by default, cellspacing="1", which is one pixel of space between the cells; cellspacing="10" would be 10 pixels of space. Tag: TABLE Attribute: CELLSPACING Values: integers representing number of pixels between cells. Description: creates space between cells in a table. Example (border of 10, cellspacing of 10): <table border="10" cellspacing="10"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1

2

Example (border of 1, cellspacing of 20): <table border="1" cellspacing="20"> <tr> <th>Goo</th> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 30 of 40


name

10/24/10 7:17 PM

<th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo

Gah

1

2

Another attribute for table: CELLPADDING. Cellpadding is the space between the content of the cell and the edge of the cell. Default cellpadding values vary cross-browser and cross-platform, but are usually about 1 to 2 pixels. Tag: TABLE Attribute: CELLPADDING Values: integers representing number of pixels between content and edge of cell. Description: creates space between content in a cell and the edge of a cell. One pixel cellpadding: <table border="1" cellpadding="1"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1 2 Fifteen pixel cellpadding: <table border="1" cellpadding="15"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 31 of 40


name

10/24/10 7:17 PM

Displayed: Goo

Gah

1

2

Fifteen pixel border, cellspacing, and cellpadding: <table border="15" cellspacing="15" cellpadding="15"> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed:

Goo

Gah

1

2

Another attribute for table: BGCOLOR. Bgcolor allows you to set the background color for a single cell, a row of cells, or an entire table. Tag: TABLE, TR, TH, TD Attribute: BGCOLOR Values: hex codes (#FFFFFF, #3399CC) or named colors (red, blue, etc) Description: colors tables, table rows, and table cells. Example: <table border="1" bgcolor="#FFCCCC"> <!-- the first row reflects the general table color --> <tr> <th>Goo</th> <th>Gah</th> <th>Gulp</th> </tr> <!-- the second row is colored via the TR tag --> <tr bgcolor="#CCFFFF"> <td>1</td> <td>2</td> http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 32 of 40


name

10/24/10 7:17 PM

<td>3</td> </tr> <!-- the third row has individually colored cells --> <tr> <td bgcolor="#FFFF99">1</td> <td bgcolor="#FFFFFF">2</td> <td bgcolor="#FFFF99">3</td> </tr> </table>

Displayed: Goo Gah Gulp 1

2

3

1

2

3

NOTES: If you want consistent appearance cross-platform and cross-browser, the BGCOLOR attribute should ONLY be added to TH and TD tags. Secondly, if you desire to create an empty colored cell, you should place an &ampnbsp inside of the cell. Lastly, you may also add the BACKGROUND attribute to the table, tr, th, and td tags. The CAPTION tag allows you to create a caption above or below the table which describes the purpose of the table. The CAPTION tag is usually placed just inside the opening TABLE tag, and has one important attribute, ALIGN. ALIGN tells the browser whether to display the caption at the top of the table (default) or the bottom. Tag: CAPTION (always closes) Attribute: ALIGN Values: top, bottom Description: CAPTION creates a caption for a table which displays above or below the table. The caption is automatically centered but not bold-faced. Example: <table border="1"> <caption>Table 1.1</caption> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Table 1.1 Goo Gah 1 2 Example: http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 33 of 40


name

10/24/10 7:17 PM

<table border="1"> <caption align="bottom">Table 1.1</caption> <tr> <th>Goo</th> <th>Gah</th> </tr> <tr> <td>1</td> <td>2</td> </tr> </table>

Displayed: Goo Gah 1 2 Table 1.1

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 34 of 40


name

10/24/10 7:17 PM

Creating Fixed Width Tables Fixed width tables require careful handling, and are dependent on very strict coding practices. The rigidity of these practices is due to the algorithms used by most browsers to draw tables. Remember that HTML has changed a very great deal over the years, and that most web browsers were built using code written in the early 1990's, when HTML was quite different than it is now. The browsers are changing slowly, but for the foreseeable future we must use modern, standards-compliant coding practices in combination with unusually restrictive syntax requirements in order to achieve consistent, reliable results. Here is a very simple fixed width table: <table width="250" border="1"> <tr> <th>Pets</th> <th>Colors</th> </tr> <tr> <td>Cats</td> <td>Red</td> </tr> <tr> <td>Dogs</td> <td>Blue</td> </tr> </table>

Displayed: Pets Cats Dogs

Colors Red Blue

As you can see, this table is 250 pixels wide. The HEIGHT attribute is not usually set for real world tables, to allow the table to expand or contract to fit the available content. Fixed width tables, when BORDER="0", are demonstrably and actually the width they proclaim; they are the only constructions in HTML, besides images, which deliver precise sizes. Individual table cells, sadly, can NOT be set to precise sizes using the WIDTH attribute of the TH or TD tags. Individual table cells may only be reliably sized using GIFs, not the WIDTH attribute. The WIDTH attribute of the TH and TD tags produces results which may or MAY NOT be approximately the size requested; they are not accurate. To achieve accurate and consistent table cell widths, tables must have most of their built-in spacing taken out. BORDER, CELLPADDING, and CELLSPACING must all be set to "0", i.e. <table width="500" border="0" cellpadding="0" cellspacing="0">. Spacing between columns of cells, then, must be created with table cells between the main columns; these "spacer" columns of cells must be filled with some sort of "spacer" GIFs.

Spacer GIFs http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 35 of 40


name

10/24/10 7:17 PM

A spacer GIF is a 3 pixel by 3 pixel GIF which is the same color as the background color of your web page. Realistically, only three colors of spacer GIFs are used: white, black, and transparent (the transparent spacer is used with all background colors and designs except white and black). Because spacer GIFs are a flat color (or transparent), they may be resized safely in the IMG tag using the WIDTH and HEIGHT attributes. <img src="spacer.gif" width="125" height="15" />

Note: Do NOT use 1 pixel by 1 pixel spacer GIFs, as these are not properly recognized by all web browsers; 3 pixel by 3 pixel GIFs are a safe spacer GIF size. Spacer gifs can also be easily created in Paint Shop Pro or Photoshop. An alternative to using spacer gifs is to use   as the content of a table cell. For example: <table width="250" border="1"> <tr> <th>Pets</th> <th width="30"> </th> <th>Colors</th> </tr> <tr> <td>Cats</td> <td width="30"> </td> <td>Red</td> </tr> <tr> <td>Dogs</td> <td width="30"> </td> <td>Blue</td> </tr> </table>

Displayed: Pets Cats Dogs

Colors Red Blue

More About Fixed Width Tables Pages containing real-world tables often have BODY tags set to display content directly against the edge of the browser window (without the browser-generated white space around the margins of the web page, as this space is inconsistent from browser to browser). To remove the browser-generated space around the content of a web page, the following four attributes of the BODY tag must be set equal to "0": MARGINHEIGHT and MARGINWIDTH (for Firefox), and LEFTMARGIN and TOPMARGIN (for Internet Explorer). <body marginheight="0" marginwidth="0" leftmargin="0" topmargin="0">

Removing the margin from a web page is useful if we have graphical content which we would like to have rest against the edge of the browser window, as in this example. If we take our text-based table from the previous section above, however, and place it immediately below the graphical table from the preceding example, the results are less than satisfactory; this http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 36 of 40


name

10/24/10 7:17 PM

example shows what I mean. Although the spacer GIF row at the top of the table prevents the columns of text from slamming into the top of the header table, notice how the text in the left column runs into the left side of the browser window. This problem can be avoided by creating an extra column on the left side of the text-based table which generates a gutter, as demonstrated in this example. Placing multiple tables into a web page, one atop the other (as seen in the examples above), is a very common practice; it allows for tables with different numbers of columns (or different widths of columns) to appear easily on the same page. Sometimes, complex elements within a column of a table are created using an additional TABLE or set of TABLEs nested within the cell; we'll look into nesting tables within table cells at greater length in a later section. You may nest as many sibling tables as you like inside of a parent table cell. It is important to note, however, that you must NEVER nest tables more than one level deep (i.e. no grandchild or greatgrandchild nested tables). In other words, don't try to nest a table inside of one of your nested table's cells; that is forbidden. Nesting tables more than one level deep creates printing and display difficulties that you will want to avoid.

Comments Because real-world tables can become very complex and lengthy, make certain to use HTML comments to mark the beginning and ending of important areas where content is likely to be inserted or change regularly. This will help yourself and others find the correct insertion point for content quickly and easily in the hundreds or thousands of lines of your HTML code. Example (abbreviated): <td valign="top"> <!-- Begin Main Area --> <p>Content here...</p> <!-- End Main Area --> </td>

Example (abbreviated): <!-- Begin Article One --> <table width="500" border="0" cellpadding="0" cellspacing="0"> <tr> <td>Some content...</td> </tr> </table> <!-- End Article One -->

Printable Pages Never use tables to hold printable content, especially if they have been modified with CSS; you'll get very irregular printed results. Create printable pages with vanilla HTML, no TABLES! Better yet, if you have the time and inclination, create printable and downloadable Adobe Acrobat (PDF) files, which are the standard for web-based documentation, as well as being very consistent in appearance cross-platform (much more so than HTML pages). http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 37 of 40


name

10/24/10 7:17 PM

Miscellaneous Never put content in a cell which would make that cell BIGGER than your defined column width; you'll get very irregular results if you do.

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 38 of 40


name

10/24/10 7:17 PM

Variable Width Tables Variable width tables are always created by using percentage values in the WIDTH property of the TABLE tag; this percentage represents some percentage of the browser window. Unless otherwise specified, a table is always aligned left. At 100%, obviously, the table would fill the entire width of the browser window. At lesser percentages, you might want to set the ALIGN attribute of the TABLE tag equal to "center". Example: <table border="0" width="90%" align="center"> <tr> <td bgcolor="#99FFFF"> <p>Some Content...</p> </td> </tr> </table>

Displayed: Some Content...

If you want your variable width table to extend right up to the edge of the browser window, of course, you will need to set the WIDTH attribute of the TABLE tag to 100%, as well as to set the MARGINHEIGHT, MARGINWIDTH, LEFTMARGIN, and TOPMARGIN attributes of the BODY tag equal to 0. Multiple column variable width tables require special handling. In most ways, you should treat them as you would a fixed width table. There are certain differences to be aware of, however. Firstly, no column can retain a fixed width. In other words, you can NOT have one column which remains the same size while other columns grow or shrink. All columns will distort to take up some given percentage of the available table width. To get columns to have SOME stability, you must decide upon a MINIMUM width for each column in the table. As a browser window grows narrower, at some point the table will become too squashed; when is that point? What is the minimum width to which your table may safely collapse? Once you have decided upon a minimum table width and a minimum width for each column, you must create graphics for each of the cells in the FIRST row of the table; these graphics must define the minimum width of EVERY column. As the browser window widens, the columns will expand proportionally to one another based on the size of the graphics in the first row of the table. In addition, by placing graphics of a certain size in the first row, you will prevent the table from collapsing any single column beyond the width of the graphic in that column. You may then create the rest of your table, just as you would a fixed width table. 100% graphics layouts beyond the first row, however, are not advisable, as graphics may separate irregularly as the table expands. Most "liquid" tables rely heavily on text for column content, as text is infinitely more malleable and forgiving than graphical content. Remember: graphics can NOT be resized on the fly as the table expands! Experiment, too, with nested tables; I have seen some very interesting effects created with fixed and variable width tables nested within cells of a variable width table. http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 39 of 40


name

10/24/10 7:17 PM

To view a video tutorial about validating a webpage using XHTML, please click here.

http://thewebparrots.com/cnit132/vidLessons/ValXHTML/

http://insight.ccsf.edu/mod/book/print.php?id=136074

Page 40 of 40


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Book 3: Cascading Style Sheets I Book for Weeks 5-6:

Cascading Style Sheets I

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 3: Cascading Style Sheets I Printed by: Donald Siino Date: Monday, 16 August 2010, 02:50 PM

1 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Table of Contents 1 Introduction to Style Sheets 2 Basic Concepts 3 Basic CSS Syntax: Introduction 4 Basic CSS Syntax: Property Syntax 5 Basic CSS Syntax: Defining HTML Tags (Selectors) Using Properties 6 Basic CSS Syntax: White Space in Declarations 7 Basic CSS Syntax: Grouping Selectors 8 Basic CSS Syntax: Comments 9 Basic CSS Syntax: Contextual Selectors 10 Making a CSS Document 11 Overview of Cascading Style Sheet Types: Linked, Embedded, Inline 12 Embedded Style Sheets 13 Linked Style Sheets 14 Inline Style Sheets 15 CLASS 16 Consistent Font Size Cross-Browser and Cross-Platform 17 Pseudo-Class 18 Units of Measurement and Color 19 Selected Properties 20 ID 21 Inheritance 22 CSS: Conclusion

2 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Reference in Musciano Book - Ch. 8 Introduction to Style Sheets As of HTML 4.0, structure and appearance in web programming have been separated. HTML, which marks things like lists, paragraphs, tables, images, etc, provides the STRUCTURAL markup, saying what something IS rather than what it looks like (for the most part). CSS (Cascading Style Sheets), then, defines all of the APPEARANCE information for HTML code, describing how the HTML-marked text will lay out, what kind of line-spacing it will have, what color it will be, how the background images will tile or be positioned, margin spacing, text indents, etc. To put it another way, CSS redefines the appearance of HTML tags (over-riding the web browser default settings), and allows for much greater sophistication of text treatment than was possible with HTML alone. CSS even allows you to position elements absolutely on an HTML page with pixel-perfect accuracy, and opens the door to so-called "Dynamic HTML" pages. In this module, I will outline the most essential features of CSS, in brief. I will not have enough time to really dig into CSS in any depth, but, if you are interested in more information, there is an excellent book available: "Cascading Style Sheets: The Definitive Guide" by Eric A. Meyer, O'Reilly and Associates, Publisher, ISBN#:1-56592-622-6. CSS has been supported by all of the major browsers, to one degree or another, since 1997. Modern CSS implementation is pretty good, but, as long as we are supporting some older browsers, we must be careful as to which CSS properties we use. Even today, cross-browser and cross-platform testing is essential to ensure consistent appearance of CSS-defined HTML pages, as CSS implementation varies between browsers and platforms. The latest official information about CSS standards is available from the World Wide Web Consortium (the international web standards organization) at http://www.w3.org/. You should always validate your CSS code via the CSS Validator. Don't expect CSS to be perfect. Although it does improve the appearance of your XHTML pages, it does not achieve perfect uniformity of appearance cross-browser and cross-platform. Despite the unevenness of its implementation, however, CSS is still far superior to the deprecated FONT tag, or any of the other deprecated tags and attributes from HTML, and can be an enormous help to you in creating beautiful web pages.

3 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic Concepts In the past, web programmers had to program all appearance information for a page using HTML tags, marking each individual item on a page separately. If someone later decided that they didn't like the way the website looked, the programmer would have to go in and change all of the HTML tags separately, one at a time, a tedious and time consuming task. In addition, the control possible over HTML appearance using only HTML tags was primitive, at best. CSS has greatly improved this situation. Not only does CSS allow for much greater control over HTML appearance, it also provides a mechanism for making global appearance changes to a group of HTML pages, or even an entire website. CSS allows you to define what HTML tags will look like, and how they will behave (to some degree). CSS also allows you to create external ".css" files, which contain all of the HTML tag appearance information. These ".css" external style sheet documents can then be applied to as many HTML pages as you like. With a single change made to a ".css" document, you can change the appearance of EVERY HTML page attached to that ".css" document, a great convenience compared to the old methods of changing each individual HTML tag on each page by hand. And CSS gives you a tremendous amount of control over every aspect of HTML tag appearance, from color and spacing to position and behavior. Because the HTML's appearance characteristics are entirely separate from the HTML itself, you can actually substitute ".css" style sheets on a website whenever you like, changing the look and feel of a website instantaneously, at will. With tremendous power over HTML tag appearance, and the ability to make changes to that appearance quickly and easily, CSS allows the web programmer great flexibility when designing websites. With this increased control, however, comes a potential for greater complexity, especially in the ".css" documents themselves. A thorough understanding of CSS principles is necessary, therefore, both to create your own CSS-enhanced websites, and to edit the CSS-enhanced websites of others.

4 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Introduction CSS does NOT use the same syntax as HTML; it is a completely separate language. In CSS, you redefine the appearance of HTML tags using PROPERTIES; these properties follow a specific syntax, which I will outline momentarily. When you redefine an HTML tag's appearance using CSS properties, you override the web browser's default settings; conversely, any property which you do NOT define reverts to the browser's default setting. For instance, if you redefine the B (bold) tag to be green 48 point Arial, but you do NOT specify its boldness (font-weight) property, the browser will automatically revert to its default setting for boldness, displaying the B tag as BOLD green 48 point Arial. In another example, if you do NOT define the H1 tag's appearance in CSS, the H1 tag will display using the browser's default settings. Again, anything you define using CSS will override the web browser's default appearance settings; anything which you do NOT define will display using the browser's default settings. Before we talk precisely about how you redefine an HTML tag in CSS, let's talk a little bit about CSS property syntax itself.

5 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Property Syntax Style sheet properties are divided into two parts: 1. property name 2. value The property name and the value are separated by a colon (:). The entire property ends with a semi-colon (;). Generic Example: property-name:value;

Actual Example (setting the font-size property to be 24 point): font-size:24pt;

Note: A property name NEVER has any spaces in it. An individual value NEVER has any spaces in it. There MAY be a space after the colon. The following example is acceptable: font-size: 24pt;

In the above example, I have placed a space after the colon between the property name and value. Again, this is permissible. The following example is WRONG: font size:24pt;

In the above example, I have placed a space in the property name; this is illegal and will cause your CSS to break. The actual property name is "font-size", not "font size". The following example is also WRONG: font-size:24 pt;

In the above example, I have placed a space between the number and the type of measurement unit in the value of the property definition; this is illegal, and will cause your CSS to break. The actual value is "24pt", NOT "24 pt" (which means something COMPLETELY different in CSS). As you can probably already tell, CSS is MUCH more particular about syntax variations than regular HTML. You must be extremely careful with your syntax in CSS, or your CSS will fail to operate. You will also notice that there are NO equals signs (=) or quote marks ("") in CSS. Although

6 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

we are dealing with CSS properties for tags which have some parallels in HTML attribute syntax, the actual syntax constructs are completely different. CSS IS NOT HTML!

7 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Defining HTML Tags (Selectors) Using Properties An HTML tag's appearance properties are defined in CSS using the following syntax: tagname { }

First, you type in the tag name, whatever it is, followed by a space, then an opening curly-brace followed by a closing curly-brace (the curly-brace symbols are right above the "return" or "enter" key on your computer keyboard). This is called a "declaration". You will place the properties that you want to define for the tag inside the curly braces; you may define as many properties in a declaration for a given tag as you want. Generic Declaration Example: tagname { property-name:value; }

Generic Declaration Example with Multiple Properties: tagname { property-name:value; property-name1:value1; property-name2:value2; }

Real Declaration Example: p { font-size:24pt; color:#000000; text-align:left; }

In the above declaration, I have reset the p tag to be 24 point, black, and aligned left. The tagname portion of the declarations shown above is called the "selector". The "selector" is whatever tag you're currently defining in CSS. Example: selector { property-name:value; }

means the same as: tagname { property-name:value; }

I mention this, because the official CSS standards refer to the tagname as the "selector", and I don't want you to be confused by the difference in the terminology. It all means the same thing. To prevent confusion, I will refer to the tagname portion of the CSS declaration of a tag as the "selector" from now on. Note: when declaring the selector in CSS, make certain that you "match case" with the way the HTML tags are spelled in your HTML pages. Since we're all now using all-lower-case tag names in HTML, it is important to use all-lower-case selectors in CSS, as well.

8 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: White Space in Declarations Some white space within CSS declarations is permissible, even recommended. We are no longer dealing with HTML, so indentation of properties is possible. Acceptable: p { font-size:24pt; color:#000000; text-align:left; }

Also Acceptable: p { font-size:24pt; color:#000000; text-align:left; }

When you have a large number of properties in a declaration, you may wish to place each property on its own line, indenting the properties in the manner shown above; this is perfectly acceptable, even de rigueur, making the CSS easier to read and analyze.

9 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Defining Common Properties for Multiple Selectors (Grouping Selectors) You may want to define common properties for a group of individual selectors. Say, for instance, that you know that your H1, H2, and H3 tags are all going to be center-aligned and black, but they're all going to be different sizes. Instead of creating three separate declarations which repeat common properties again and again, you can assign those common properties to the tags by grouping the selectors together in a declaration, separated with commas. Example: h1, h2, h3 { text-align:center; color:#000000; }

You may then assign the specific, individual properties for each tag in SEPARATE declarations. Example: h1, h2, h3 { text-align:center; color:#000000; } h1 { font-size:36pt; } h2 { font-size:24pt; } h3 { font-size:18pt; }

Example: h2, p, td { color:#330000; } h2 { font-size:24pt; } p { font-size:14pt; text-align:right; } td { font-size:12pt; text-align:center; }

Example: h1, h2, p { text-align:center; } h1, h2 { color:#660066; } h1 { font-size:36pt; } h2 { font-size:24pt; } p { color:#000000; font-size:14pt; }

This kind of power can get you in trouble, however. You must be VERY careful NOT to repeat properties for the same tag within separate declarations. The following example would be WRONG: h2, p { color:#000000; } p { font-size:24pt; color:#330000; }

In the above example, I have repeated the color property TWICE for ordinary instances of the P tag, which could potentially confuse the browser. Don't do this!

10 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Comments Comments are little statements inserted into a block of code which explain the purpose of that section of code, or make notes to yourself or others, or hide things which need to be invisible to the user. HTML comments look like this: <!-- This is a comment in HTML -->

CSS comments do NOT look like HTML comments; they follow traditional C/C++ comment syntax. Single line comments are prefixed by slash-slash (//) and end when you type a carriage return. Multiple line comments are prefixed by slash-asterisk (/*) and end with an asterisk-slash (*/). Example (single line comment): // this is a single line comment Example (multiple line comments): /* this is multiple line comment syntax on a single line */ /* This is also a multiple line comment, with multiple lines in it this time. */

Having said this, single-line comments are broken in CSS; do NOT use single line comment syntax! Remember: use only MULTIPLE LINE comments when writing CSS! Note: because CSS documents can get very complicated, you will be using a lot of comments to clarify your code, to yourself and others. Trust me, you will need to write notes to remind yourself of what you were doing, so that six months down the line, you'll be able to remember what you did without re-analyzing all of the CSS again!

11 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Basic CSS Syntax: Contextual Selectors Contextual selectors allow you to define the appearance for HTML tags in parent-child relationships with other HTML tags. In the following example, I have created two instances of the B (bold) tag: one by itself, and one where it appears as a child object of a P (paragraph) tag. Example: <b>Here is some bold text.</b> <p>Here is a paragraph with a <b>bold</b> word in it.</p>

Now, I could make one CSS declaration which would define all instances of the B tag uniformly, as I have done in the past: b { font-weight:bold; color:#000000; }

But what if I want the B tag when it appears as a child of the P tag to look different than the B tag by itself? The appearance of these B tags can be defined separately using a contextual selector in a CSS declaration. A contextual selector for a declaration states the parent selector first, then a space, then the child selector, followed by a space and the curly-braces containing the properties. Generic Example: parenttagname childtagname { property:value; etc... }

Actual Example (defining the B tag when it is a child of the P tag): p b { color:#660066; font-weight:bold; }

Using contextual selectors, I can define how an HTML tag will look when it is IN CONTEXT of another specific HTML tag (in other words, when it is a child of another tag). For instance, I can define the B tag as a child of the P tag separately from the B tag as a child of the TH tag; I can define the tag appearance based on its CONTEXT, hence the term CONTEXTUAL selector. I can define properties of the B tag generally, and I can ALSO more specifically redefine some or all of those properties when the B tag appears as a child of the P tag. Example: b { font-weight:bold; color:#000000; } p b { color:#660066; }

In the first CSS declaration above, I have told the browser to make the B tag appear bold and black. In the second declaration, I have used a contextual selector to tell the browser to make the B tag (when it appears as a child of the P tag) appear dark violet. Because I have NOT

12 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

specified the font-weight property AGAIN within the second CSS declaration above, the B tag as child of the P tag will INHERIT the font-weight (boldness) property from the general B tag declaration. Remember: you can define the main properties for a tag in a general declaration (like the one for the B tag above), then override one or more of the properties defined for the tag in different CONTEXTS (situations) using contextual selectors in CSS declarations, as you can also see above. When creating contextual selectors, you MUST separate the different selectors with spaces. The following example is WRONG: pb { color:#660066; }

I have NOT used a contextual selector in the above example; Instead, I have made a CSS declaration for some non-existent tag called "pb", which won't do us any good. When using contextual selectors, I can define contexts for a given tag with as much "granularity" as I like. In other words, I can specify very extensive ancestral relationships using multiple contextual selectors in a CSS declaration, each selector separated by a space. Example: b { color:#000000; } p b { color:#660066; } table tr td b { color:#006600; } table tr td p b { color:#000066; }

In the above example, I have defined the B tag: 1. 2. 3. 4.

by itself as black in context of the P tag as dark violet in context of a TD cell in a TABLE as dark green in context of a P within a TD cell in a TABLE as dark blue

Example: table table table table

tr tr tr tr

td th td th

{ color:#000000; } { color:#660066; } table tr td { color:#006600; } table tr td { color:#000066; }

In the above example, I have defined the color for text in TD and TH cells within a TABLE (black text for TD, dark violet text for TH). I have also defined the color for text in TD cells for a TABLE nested within a TD tag in another TABLE, contrasted with the next declaration, where I have defined the color for text in TD cells for a TABLE nested within a TH tag of another TABLE; so, I am differentiating between TD cells of tables nested within TD tags, versus TD cells of tables nested within TH tags. As you can see, I can become extremely specific about differences in tag appearance in different contexts, using CSS declarations and

13 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

contextual selectors. You may or may not ever need to access this level of granularity, but it's important to know how to do so, if you should ever need it. I would also use this sort of contextual selector when defining list and sub-list appearance: ul li { list-style-type:disc; } ul ul li { list-style-type:square; }

In the above example, I have defined the LI tag for an unordered list to use the disc-type bullet, while defining the LI tag for a nested unordered list (or sub-list) to use the square-type bullet. Contextual selectors provide a very powerful mechanism for differentiating tag appearance based on the context of the tag. There is also another way to differentiate tags, using something called a CLASS; we'll discuss classes in a later section.

14 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Making a CSS Document Making a CSS document is simplicity itself. A CSS document is nothing but a plain text (ASCII) file, saved with the ".css" file name extension; remember to follow all of the regular naming rules for any file name on the Web (NO SPACES IN THE NAME!). Example CSS Document Names: myStyles.css linksty.css steve.css

The content for a CSS document usually follows this format: 1. Place a comment at the beginning of the code, indicating your name and contact information, and what this CSS document is being used for; this information will allow other programmers (who are presumably working with you, or who are in your company) to contact you with questions about your work, and to figure out what project this CSS document applies to. 2. Follow the comment with all of your CSS declarations. 3. If necessary, add comments between your CSS declarations, indicating what they are for. Example: /* Style Sheet for Widget Website Steve Rubin -- srubin@peoplepc.com */ /* Begin General Site Styles */ p { color:#000000; font-size:14pt; } b { font-weight:bold; } /* End General Site Styles */ /* Begin Home Page Styles */ etc...

Remember: there are NO HTML tags in a CSS document. CSS IS NOT HTML! There is no HEAD, no BODY, no TITLE, no HTML tag, no HTML of any kind! A CSS document is linked to an HTML page using a special tag on the HTML page itself, not on the CSS document; we'll talk about the specifics of this linking process in a later section. In a CSS document, you are just defining the way HTML is going to look; you're not actually using HTML.

15 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Overview of Cascading Style Sheet Types: Linked, Embedded, Inline There are three main types of cascading style sheets: linked, embedded, and inline. Linked style sheets are the preferred form of style sheet. An external ASCII/plain-text document (named with the ".css" file name extension) contains the style sheet information. This external text-only document is linked to the HEAD of an HTML page using the LINK tag. A single external style sheet may be linked to as many HTML pages as you wish, and changes made to this external linked style sheet will automatically be reflected on every HTML page linked to it (a tremendous convenience). Embedded style sheets use CSS declarations placed within a STYLE tag in the HEAD of a particular HTML page. Because this embedded style information is inside of the HEAD of one HTML page, it affects only the appearance of tags on that HTML page, and can not be applied to any other HTML pages. In every other respect, however, embedded style sheets use the same basic CSS syntax as external linked style sheets (redefining the appearance of HTML tags). Inline style sheets place style information in a SPAN tag inside the BODY of an HTML page, and are used in much the same way as the old FONT tag. Inline style sheets are the least flexible of all style sheets, and have all of the inconvenience of the old FONT tag (although with more control and power). Inline style sheets apply to only one single element inside the BODY of an HTML page (the SPAN tag), and must all be changed individually when a change to the look-and-feel of the site is proposed. Inline style sheets can only use a limited portion of basic CSS syntax; they do not affect HTML tags on a page as a whole, they merely affect whatever is marked by their particular SPAN tag. In general, use linked style sheets whenever possible; they are the most flexible, the most portable, the most convenient style sheet. If you are creating only one HTML page that uses CSS, an embedded style sheet may be appropriate. Inline style sheets are only useful if you do not have access to the HEAD of the HTML page in question. In other words, if you are adding information to the BODY of an HTML page through some web-based mechanism but cannot affect the HEAD of that page, you might find inline style sheets helpful. Otherwise, you will probably never want to use inline style sheets.

The Cascade As you may have gathered, more than one style sheet can potentially be applied to a given HTML page at a time. When two or more style sheets are in conflict (referring to the same properties of the same tag), this conflict must be resolved. Conflict resolution in style sheets is called the "cascade". I am not going to go into details about the cascade; it is a very involved topic. In general, however, the cascade is resolved by the specificity of the style sheet in question. Remember the following rules:

16 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Style information in a linked style sheet overrides the web browser's default appearance settings. Style information in an embedded style sheet overrides the web browser's default appearance settings, as well as any linked style sheet information attached to that HTML page. Inline style sheets override the web browser's default appearance settings, as well as both linked and embedded style sheets attached to that HTML page. In order of specificity (most specific to least specific): 1. 2. 3. 4.

17 of 43

Inline Embedded Linked Web Browser Default Settings

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Embedded Style Sheets An embedded style sheet is style information placed within a STYLE tag in the HEAD section of a single HTML page. Tag: STYLE (always closes) Attribute: TYPE Value: text/css Example (abbreviated): <head> <style type="text/css"> /* style information here */ </style> </head>

Example (abbreviated): <head> <style type="text/css"> p { font-size:14pt; color:#000000; } b { font-weight:bold; } </style> </head>

Finally, you may place any style information or declarations into an embedded style sheet that you would place into a linked external style sheet. The style information in an embedded style sheet, however, ONLY applies to that one HTML page.

18 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Linked Style Sheets An external CSS document is attached to an HTML page using the LINK tag. The LINK tag, like IMG and BR, doesn't ordinarily close in HTML, but if you are using XHTML, then you must use the "space-close-slash" before the closing bracket syntax. Example (abbreviated): <link>

The LINK tag always goes in the HEAD of an XHTML page. LINK requires three attributes: REL, TYPE, and HREF. Tag: LINK Attribute: REL Value: stylesheet Tag: LINK Attribute: TYPE Value: text/css Tag: LINK Attribute: HREF Value: any URL, relative or absolute, to the external CSS document that you want to link to the HTML page. Example using HTML: <link rel="stylesheet" type="text/css" href="myStyles.css" />

Example using HTML(in context): <html> <head> <title>My Test Page</title> <link rel="stylesheet" type="text/css" href="myStyles.css" /> </head> <body> <p>Some text...</p> </body> </html>

Note: Despite the fact that, at this time, the LINK tag is only used to attach external CSS documents to an XHTML page, the REL, and TYPE attributes of the LINK tag are there to tell the web browser that this particular LINK tag is REALLY a CSS LINK tag. These attributes allow the LINK tag to be expanded, one day, to work with some other technology. In the meantime, however, REL and TYPE will always be the values indicated above.

19 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Inline Style Sheets Inline style sheets mainly use the SPAN tag within the BODY of an HTML page to add style to selected text. Example (abbreviated): <span>Here is some text.</span>

SPAN requires one attribute: STYLE. The STYLE attribute of the SPAN tag will be set to some number of properties which would then apply to that one SPAN tag. Example: <p>Here is <span style="font-size:24pt; color:#FF0000;">some text.</span></p>

Displayed: Here is

some text.

Example: <p>Here is <span style="font-size:36pt; color:#660066; font-family:'Arial', 'Helvetica', sans-serif;">some more text.</span></p> Displayed:

Here is

some more text.

In the above example, you will notice that I have placed the quoted font names for font-family in SINGLE-quotes rather than double-quotes. Since you can NOT put extra double-quote marks inside an attribute value in HTML, you must substitute single-quote marks. As you can see, inline style sheets do NOT redefine tags; they merely mark text in HTML using the SPAN tag. Again, inline style sheets override both embedded style sheets and linked style sheets applying to the same HTML page. The STYLE attribute may ALSO be added to ordinary HTML tags, as in the following example: <p style="font-size:36pt;">Here is some more text.</p>

Displayed:

20 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Here is some text. Warning: This sort of inline style does NOT always behave predictably when in conflict with linked or embedded style sheets. Inline styles are useful only under very specialized circumstances, such as when you don't have access to putting tags in the HEAD of an HTML page. Inline styles can become burdensome very rapidly if you want to change the appearance of your HTML page, since you have to go back in and change every SPAN tag separately. In general, mainly use linked or embedded style sheets when applying CSS to HTML pages. On the other hand, there are times when using an inline style or two can be very convenient.

21 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

CLASS We've talked about defining tags using selectors, contextual selectors, and properties in CSS declarations. But what happens if you want to define several variations on a single tag, such as the P tag? In traditional publishing, there are body text paragraphs, and callout paragraphs, and footnote paragraphs, among many many others; the CSS syntax we have learned so far does not allow us to create multiple variations on a single tag (beyond the limited capabilities provided by contextual selectors in CSS declarations). To define more than one version of an HTML tag, you need to use a CLASS. Class declarations in CSS are prefixed with a dot (.), followed by the name of the class, a space, and the curly-braces containing the style properties; as with any CSS declaration, you may define as many properties for a class declaration as you wish. Example: .warning { color:#FF0000; }

In the above example, I have created a CSS declaration defining a class called "warning", which causes text to be bright red. This syntax creates a GENERAL class, which may be applied to ANY HTML tag. Obviously, this class declaration must be placed within either a linked or embedded style sheet. In an HTML page connected to this CSS declaration, then, I would add the CLASS attribute to any HTML tag; the value of the CLASS attribute would be the name of the desired class in the style sheet, "warning". Example: <p class="warning">This paragraph has had the warning class applied to it.</p>

Because I have created a general "warning" class, I can apply it to other tags, as well. Example: <p>Here is a paragraph with a <b class="warning">special</b> word in it.</p>

Example Page (with embedded style sheet): <html> <head> <title>Example CSS Page</title> <style type="text/css"> p { color:#000000; } .warning { color:#FF0000; }

22 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

</style> </head> <body> <p class="warning">This paragraph has had the warning class applied to it.</p> <p>Here is a paragraph with a <b class="warning">special</b> word in it.</p> </body> </html>

Here is the above example displayed. Now, if you want to restrict usage of a class declaration to ONE kind of HTML tag, you can specify that it in the class declaration, as well, by adding the desired tag selector before the dot (.) character. Example: p.warning { color:#FF0000; }

By adding the P tag selector before the dot (.) character in the above class declaration, I have restricted usage of this class to the P tag. In the following code, then, only P tags would be able to accept the "warning" class; other tags will NOT be able to use the "warning" class. Example (in context): <html> <head> <title>Example CSS Page</title> <style type="text/css"> p { color:#000000; } p.warning { color:#FF0000; } </style> </head> <body> <p class="warning">This paragraph has had the warning class applied to it.</p> <p>Here is a paragraph with a <b class="warning">special</b> word in it.</p> </body> </html>

Here is the above example displayed. Notice how the B tag is now unaffected by the "warning" class?

23 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

I may also use contextual selectors before the dot (.) character in a class declaration to further restrict class usage. For instance, I could restrict the "warning" class to B tags which were children of P tags by using the following syntax: p b.warning { color:#FF0000; }

Example (in context): <html> <head> <title>Example CSS Page</title> <style type="text/css"> p { color:#000000; } p b.warning { color:#FF0000; } </style> </head> <body> <p class="warning">This paragraph has NOT had the warning class applied to it.</p> <p>Here is a paragraph with a <b class="warning">special</b> word in it.</p> </body> </html>

Here is the above example displayed. Notice how the warning class in the above example applies only to B tags which are children of P tags, and NOT the P tag by itself? Restrictive class declarations can prevent you from applying inappropriate class styles to HTML tags, and can be useful if you are creating extremely complicated style sheets. Class names must NOT be repeated in a style sheet. You can NOT, for instance, create two classes of the same name for different tags. Example (WRONG): p.warning { color:#FF0000; } p b.warning { color:#FFFF00; }

Since every class name must be unique, a common practice in this circumstance is to append the name of the tag to the end of the class name, giving you unique names. Example (CORRECT): p.warningP { color:#FF0000; } p b.warningPB { color:#FFFF00; }

Although I have discussed specifics of restricting classes, most class declarations that you will make will be GENERAL classes (e.g. without a selector prefix before the dot character).

24 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

The SPAN tag may also be used in combination with the CLASS attribute. The SPAN tag itself does not have any special formatting associated with it, and lends itself well to acting as a generic shell HTML tag. In this kind of situation, the SPAN tag would NOT be considered an inline style sheet, because its CLASS style information would be defined in a linked or embedded style sheet; the SPAN tag would merely be a blank HTML tag which you could apply CSS properties to. Example: <p>Here is some text with <span class="warning">special words</span> in it.</p>

As you can imagine, classes really open up possibilities and complexities in CSS. Using the CLASS attribute and class declarations in style sheets, you can create as many different style variations for an HTML tag as you wish. You may also greatly refine the look-and-feel of your HTML pages, using a mechanism which allows for easy and rapid changes. Example: body { background:#CCCCCC; } p { font-size:18pt; color:#000000; font-family:"Times New Roman", "Times", serif; } p.callout { font-size:16pt; margin-left:1in; margin-right:1in; } p.note { font-size:12pt; } .special { font-style:italic; color:#660066; }

Example (in context): <html> <head> <title>Example CSS Page</title> <style type="text/css"> body { background:#CCCCCC; } p { font-size:18pt; color:#000000; font-family:"Times New Roman", "Times", serif; } p.callout { font-size:16pt; margin-left:1in; margin-right:1in; } p.note { font-size:12pt; } .special { font-style:italic; color:#660066; } </style> </head> <body> <p>Here is a body text paragraph. In this paragraph, I would say something, if I had something to say. Since I have nothing to say, I, like many modern politicians, will run on and on without 25 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

saying anything; making noise is so important. In another speech, Horatius Q. Vanderfeller said:</p> <p class="callout">"What is today, is yesterday, and what is tomorrow is the day after tommorrow. Time is an illusion. That's why I'm eating shrimp for dinner!"</p> <p>Here is another body paragraph.</p> <p class="note">Watch out for those silly quotations... They are very <span class="special">dangerous</span>.</p> </body> </html> Here is the above example displayed. Now, I can change that page's look-and-feel simply by changing the style sheet. In the following example, I have ONLY changed the properties in the embedded style sheet; I have changed NOTHING in the HTML itself. Note: I am using embedded style sheets simply so that you may see the code all in one place; if I were making this style sheet for the real world, I would be using a LINKED external style sheet so that I could apply these styles to MANY pages. Example: <html> <head> <title>Example CSS Page</title> <style type="text/css"> body { background:#FFCCFF; } p { font-size:16pt; color:#660066; font-family:"Arial", "Helvetica", sans-serif; } p.callout { font-size:24pt; margin-left:1in; margin-right:1in; font-family:"Times New Roman", "Times", serif; } p.note { font-size:10pt; } .special { font-style:italic; color:#FF0000; } </style> </head> <body> <p>Here is a body text paragraph. In this paragraph, I would say something, if I had something to say. Since I have nothing to say, I, like many modern politicians, will run on and on without

26 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

saying anything; making noise is so important. In another speech, Horatius Q. Vanderfeller said:</p> <p class="callout">"What is today, is yesterday, and what is tomorrow is the day after tommorrow. Time is an illusion. That's why I'm eating shrimp for dinner!"</p> <p>Here is another body paragraph.</p> <p class="note">Watch out for those silly quotations... They are very <span class="special">dangerous</span>.</p> </body> </html> And here is the above example displayed.

27 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Consistent Font Size Cross-Browser and Cross-Platform Something you may be already noticing, especially if you are working on a Macintosh, is that the point-based font sizes specified in my style sheets so far have NOT produced consistent results cross-browser and cross-platform. When setting font sizes in style sheets, you MUST use PIXEL-based values if you want consistent appearance. In your style sheets, then, instead of saying "24pt" for 24 point font size, you would need to say "24px" for 24 PIXEL font size. Here is an example from the previous section, with the font-size properties set to pixel-based rather than point-based values. Example (excerpt): body { background:#FFCCFF; } p { font-size:16px; color:#660066; font-family:"Arial", "Helvetica", sans-serif; } p.callout { font-size:24px; margin-left:1in; margin-right:1in; font-family:"Times New Roman", "Times", serif; } p.note { font-size:10px; } .special { font-style:italic; color:#FF0000; }

Here is the above example displayed, in context. Using pixel-based font sizes DOES provide consistent results across browsers and platforms. If you are a Mac-based developer, the conversion will be easy for you, since point-based and pixel-based fonts are the same size on the Mac (i.e. 12 point = 12 pixel). If you are a PC-based developer, you have a trickier job of font-size conversion. A point is 1/72 of an inch. A 12 point font, therefore, should be 12/72 of an inch tall (roughly). The Macintosh displays everything at 72 pixels per inch. One point, therefore, is technically one logical pixel tall on the Macintosh, so point-sized-font equals pixel-sized-font on the Mac. The Macintosh was originally designed to be a desktop publishing machine. On a PC, fonts are displayed by the Windows OS at 96 pixels per inch. A 12 point font, for instance, is 12/72 of an inch, 12/72 of 96 pixels is 16 pixels, therefore a 12 point font is technically 16 pixels tall on the PC. A web browser displays everything at 72 pixels per inch. When a 12 point font on the PC is displayed in a web browser, the pixels are all preserved, so the font becomes 16 pixels tall, or 16/72 of an inch (which is really 16 points). If you want to preserve what you see at "12 point font size" in a web browser on a PC, then, you must set the CSS property font-size to 16px (16 pixels). The conversion formula for the PC: point-based-font-size / 72 * 96 = pixel-based-font-size

Example Conversion for a 30 point font as viewed in a web browser on the PC: 28 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

30 / 72 * 96 = 40px

If you just do all of your design using pixel-based font sizes, you will avoid having to do these conversions. Something you should be aware of when setting fixed font-size in CSS: users will NOT be able to resize the fonts in their web browser to make them larger; this can be a problem for users whose monitors display small pixels or for users who are visually-challenged. If you are NOT providing alternate style sheets for users (which can be done with JavaScript), you MUST be careful to make your fonts large enough in your CSS declarations! Note: Users DO have the option of turning off CSS formatting of web pages via their Preferences settings, but most are not aware of this. Mac Developers Be Aware: Internet Explorer for the Mac converts CSS font-size property values to match the display of its PC counterpart, so "font-size:12pt;" will display at 16 pixels tall! This automatic conversion can be a tremendous convenience for cross-platform development work, but it can also be a trap to catch the unwary!

29 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Pseudo-Class The pseudo-class was developed to define tags with more than one state. The only tag in HTML that has more than one state is the A (anchor) tag, which has three official states: link, visited, and active. To define the A (anchor) tag, then, you need to use the pseudo-class, which is marked in a CSS declaration using the colon (:) character to separate the selector and the name of the pseudoclass. Example: a:link { color:#0000FF; } a:visited { color:#FF00FF; } a:active { color:#FF0000; }

Of course, you can define more than just color using the pseudo-class; you can define any properties you like in the pseudo-class declarations. Don't get any tricky ideas about causing the hyper-reference to get larger while the user clicks during the active state, however; you can't trigger that sort of dynamic behavior with CSS alone. Due to flaws in early web browser CSS implementations, you must ALWAYS set the pseudo-class for the A (anchor) tag when using CSS (otherwise, early Internet Explorer versions will make your hyper-references the same color as your main text color, making hyper-references and text indistinguishable from one another). You may also use contextual selectors to define different versions of the A (anchor) tag. Example: a:link { color:#0000FF; } a:visited { color:#FF00FF; } a:active { color:#FF0000; } p a:link { color:#000066; } p a:visited { color:#660066; } p a:active { color:#660000; }

Be very wary about doing this, however; users are only used to ONE set of hyper-reference colors on a page. At this time, classes of the pseudo-class are not fully supported, so you can not RELIABLY define true variations of the A (anchor) tag, as you would with normal HTML tags. However, should you wish to do so EVENTUALLY, the syntax required is straightforward. Add the dot (.) after the selector, followed by the name of the class, followed by the colon (:) character, followed by the state of the pseudo-class, then a space and the curly-braces containing the properties. Example:

30 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

a.warning:link { color:#660000; } a.warning:visited { color:#663300; } a.warning:active { color:#000000; }

This class of the pseudo-class would be added to A (anchor) tags using the CLASS attribute, as you might expect. Example: <p>Here is a <a href="http://www.yahoo.com/" class="warning">Yahoo</a>link.</p>

If, for some reason, you decide to use more than one set of hyper-reference colors on one HTML page, you had better be careful that your context makes it VERY clear which words are really hyper-references, and which ones are merely colored. To fully ensure that users recognize hyper-references on a page, it is wise to force an underline to appear below the hyper-referenced words; underlines under colored words on a web page usually indicate hyper-references. Underlines can be set using the text-decoration property with the underline value. Example (abbreviated): text-decoration:underline;

Example: a:link { color:#0000FF; text-decoration:underline; } a:visited { color:#FF00FF; text-decoration:underline; } a:active { color:#FF0000; text-decoration:underline; }

To turn OFF the underline, set the text-decoration property to the none value. Example (abbreviated): text-decoration:none;

I strongly urge you NOT to turn off the underline for the pseudo-class if you are using MORE than one set of link colors (either with contextual selectors or classes of the pseudo-class). By the same token, do NOT set an underline for something that is NOT a hyper-reference unless your context makes underlining highly appropriate. Again, most users associate underlines with hyper-references; try not to confuse your users. Lastly, a very useful pseudo-class involves the changing of a link's color when the mouse is placed or hovers over it. Example: a:hover { color:#000000; }

31 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Example (displayed): Go to Steve's web site. (On this site, notice how the links' colors and background colors change when the mouse hovers over them.) If you want only certain links to display some style when the mouse is placed or hovers over them then you should use a class. Example: <head> <style type="text/css"> a.x:hover {color: #000000; background-color: yellow; font-weight: bold;} </style> </head> <body> <h2>a:hover and class</h2> <a href="#">Hover does nothing</a><br /><br /> <a class="x" href="#">Hover with class="x"</a> Example (displayed):

32 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Units of Measurement and Color Individual values in CSS NEVER have spaces in them. The only exception to this rule is in regard to regular font names like "Times New Roman" and "Courier New", which must be enclosed in quote marks. There are three types of measurement units: percentage, absolute, and relative. Percentage units are represented using integers and the percent (%) sign in the usual manner; negative values are also allowed (when applicable). Example: 10% 200% -130%

Absolute units include in (inches), cm (centimeters), mm (millimeters), pt (points; 1 point equals 1/72nd of an inch), and pc (picas; 1 pica equals 12 points). Even though point sizes in fonts are actually relative to the size of the font itself (Times being smaller than Arial, for example, or Courier being larger than Garamond), a point is really an absolute unit of measurement. If you are NOT referring to a font, a point is an absolute value of 1/72nd of an inch. With the absolute units, you may use any number to define your value, including numbers with decimal places and negative numbers. Examples: 1.5in 25mm -.05in 2001.5mm 5cm

Relative units include em (ems), ex (ex's), and px (pixels). Pixels are considered to be relative units because monitors display pixels at different sizes. Despite this, pixels are an absolute quantity in CSS, because 1 pixel is 1/72nd of an inch as far as web pages are concerned. Pixel values are always stated using integers. Example: 100px 25px 256px

33 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

"em" and "ex" are terms from the traditional print world, and are sizes based on a given font. An "ex" is the height of a lower-case letter "x". An "em", in traditional printing, is the width of an upper-case letter "M"; an "em" in CSS, however, is the HEIGHT of an upper-case letter "M". You can define "em" and "ex" values using any number, including numbers with decimal places and negative numbers. Example: .5em -10ex

Synopsis of Measurement Unit Types Percentage Values: 50%, 100%, etc. Absolute Values: in, cm, mm, pt, pc Relative Values: em, ex, px

Colors You may use hex codes to define colors in CSS, as we have done in previous examples; I strongly recommend that you stick to web-safe color values (using digits 00, 33, 66, 99, CC, FF, as we have discussed in earlier modules). Remember that hex codes must ALWAYS start with the pound (#) sign. Example: #FFFFFF #000000 #339966

CSS also supports the named color values (white, black, blue, etc). Because the named color values are not all web-safe, however, I don't recommend that you use them. Here's the list of 16 basic named colors, for reference: black, silver, gray, white, maroon, red, purple, fuchsia, green, lime, olive, yellow, navy, blue, teal, aqua.

34 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Selected Properties I can not possibly outline every CSS property for you here. If you are interested in details, visit the World Wide Web Consortium website at http://www.w3.org/ or get Eric Meyer's book "Cascading Style Sheets: The Definitive Guide". In this section, I will outline a few of the most essential properties, as well as other important pieces of CSS information.

Text Properties Property: font-family Example: font-family:"Times New Roman", Times, serif;

As with the deprecated FONT tag with its FACE property, you need to give users more than one font choice, in case the first choice font is not loaded on their system. The first font in the list is the first choice, the second font in the list is the fallback choice if the first font is not available, etc. The desired system fonts should always be marked with quote marks. All font choices should be separated with commas. You should always end your list with one of the five generic font names; the generic font name should NOT be in quotes. Generic Font Names and their Mac/PC equivalents: serif Mac: Times PC: Times New Roman sans-serif Mac: Helvetica PC: Arial monospace Mac: Courier PC: Courier New cursive Mac: Zapf Chancery PC: Script fantasy (not fully implemented) Mac: Western PC: Comic

Property: font-size Example:

35 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

font-size:24px;

Remember: for cross-browser and cross-platform compatibility, always use pixel-based font sizes in your CSS. There are also relative values available for font-size, but they are not consistently implemented. Theoretically, they are each supposed to be 50% smaller or larger than their neighbor, but this is not always the case. "medium" is supposed to be the browser default size. Values: xx-small, x-small, small, medium, large, x-large, xx-large

There are two other relative values which DO work: smaller (50% smaller than the parent element's font) larger (50% larger than the parent element's font) Property: font-style Example: font-style:italic;

Values: normal, oblique, italic The font-style property allows you to set the italicization of your text. Note: the oblique value ONLY works if the user has an oblique version of that font loaded into the browser; unless you are using downloadable fonts (which are beyond the scope of this introductory lecture), you don't want to use the oblique value. Property: font-weight Example: font-weight:bold;

Values: bold, normal, 100, 200, 300, 400, 500, 600, 700, 800, 900 The font-weight property sets the boldness of a tag. The numerical values go from light (100) to black (900) and every boldness level in-between. As with the oblique value of the font-style property, however, the user will only see 9 levels of boldness if he/she has 9 different versions of the same font loaded in his/her machine; otherwise, the font will only be bold or normal. Property: text-decoration Example:

36 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

text-decoration:underline;

Values: none, underline, line-through Property: text-indent Example: text-indent:.5in;

The text-indent property sets the indentation of the FIRST line of text in a paragraph; the larger the text-indent value, the farther the first line will be indented into the paragraph. The text-indent property can be set to negative values to create a "hanging" indent, which pokes out from the edge of the paragraph. If you do this, the margin-left property must also be set to an equivalent positive value to offset the hanging indent; otherwise the indent will go off the side of the browser window, obscuring the first part of the line. Example (hanging indent): p { text-indent:-.5in; margin-left:.5in; }

Property: line-height Examples: line-height:120%; line-height:24px; line-height:normal;

The line-height property sets the "leading" for text, creating space between lines in a paragraph. Set to percentage values, pixel values, or "normal". Property: text-align Example: text-align:left;

Values: left, center, right, justify The text-align property is used to align things left, center, or right. With text, you can also create "justified" text, which lines up on both left and right sides. Note Regarding Text Properties You can NOT set basic font properties in the BODY tag CSS declaration and have that color and font-family and font-size trickle down reliably to child P tags and TD/TH tags, as you

37 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

might expect; sometimes it will work, most of the time it won't. You must always set text properties for the tags individually!

Margin, Border, and Padding In CSS, there are four conceptual parts of EACH element on an HTML page, whether a paragraph of text, or a single word, or a picture, or whatever: 1. 2. 3. 4.

The element itself. The padding, which is the space between the element and its border. The border. The margin, which is the space between an element's border, and the next element's margin.

The margin, border, and padding of an element may be NOTHING, of course, or each property may be set individually or collectively, at will. You may set only the margin, or you may set both margin and border but no padding, or any two in combination, or all three together. Not only can you set these properties, you can set the four sides of any of these properties individually or collectively, as well. For instance, you can set a margin of 1 inch all the way around something, or you can individually set the left, right, top, and bottom margins at different sizes. Not all of these properties are fully and consistently implemented, of course. The margin property has been fairly stable for some time, but padding and border properties are not as evenly implemented. To support all browsers consistently, use only the following properties: margin margin-left margin-right margin-top margin-bottom padding border

Note: be very careful using these properties. Setting these properties for paragraphs, for instance, works well. Setting these properties for table cells is not fully implemented. Setting these properties for images breaks the text wrap features built into many of the browsers; don't use these properties with the IMG tag (in fact, do NOT define the IMG tag in CSS at all, PERIOD, or you'll be sorry!). Do NOT set these properties for individual words or hyperreferences within an element, or you will get very inconsistent behavior cross-browser. Property: margin Example:

38 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

margin:.5in;

Values: any valid unit of measurement, relative, absolute, or percentage. The margin property sets all sides of the margin evenly (top, bottom, left, right). If you wish to set the individual sides separately, don't use the margin property; instead, use the specific margin-left, margin-right, margin-top, and margin-bottom properties. Property: padding Example: padding:.5in;

Values: only positive values using any valid unit of measurement, relative, absolute, or percentage. Property: border Example: border:1px solid #003300;

The border property requires three values: the width of the border, the style of the border, and the color of the border, each value separated by a space. You can use pretty much any value for width (although pixel values work best). There are only a couple of values for the border style which work with the version 4 browsers, the best being "solid". The color of the border can be anything. In the most modern browsers, you may set the sides of the border individually; this is not supported in the version 4 browsers, however, so be warned. Note: I must again emphasize the importance of using these properties VERY sparingly, as they can rapidly get you into trouble.

Background Properties You can use the background property for setting the background color and/or image for the BODY of an HTML page. One of the interesting features of the background property is that it may now be set for individual elements, such as paragraphs, as well! Example: p { background:url(newsletter.gif); }

Any element may theoretically have a background color or image. Use this feature sparingly, however, as it does not work in a perfectly consistent manner.

39 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

There are properties relating to backgrounds which allow you to control the manner in which the background image tiles, how often it tiles, where it tiles, where it is positioned, whether it scrolls or remains fixed on the HTML page (a watermark), etc. These properties are too numerous to explore in this brief excursion into CSS, nor are they completely or consistently implemented. For more information, refer to http://www.w3.org/.

40 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

ID An ID is identical, in many ways, to the NAME attribute in HTML; in fact, in future browsers, ID will completely replace the NAME attribute! An ID is used to identify an element for manipulation in a scripting language, such as JavaScript. An ID is declared in CSS much like a class, only using the pound (#) sign rather than a dot (.) character. Unlike a CLASS, an ID may NOT be prefaced by a selector or contextual selector; it must stand alone in the CSS code. Example: #banana { color:yellow; }

In HTML, then, I would assign an ID to an HTML tag using the ID attribute. Example: <p id="banana">This is the banana paragraph.</p>

An ID, as you might have guessed from its similarity to the NAME attribute, may ONLY be applied to ONE element on a given HTML page. IDs are mostly used with CSS-P, for positioning elements absolutely on an HTML page, and with Dynamic HTML.

41 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

Inheritance Inheritance has to do with the passing of properties from a parent object to a child object. Example: <html> <head> <title>Sample Inheritance</title> <style type="text/css"> body { background:url(bgleave.gif); } p { font-size:24px; color:#006600; } </style> </head> <body> <p>Here is some text with a <b>bold</b> word in it.</p> </body> </html>

Here is the above example displayed. In the above example, the BODY is the parent of the P tag, and the P tag is the parent of the B tag. The B tag INHERITS the font-size and color from its parent, so that both are displayed in 24px and green. The P tag, on the other hand, does NOT inherit the background property from the parent, but, rather, is background-less and floats over the parent's background image. Some properties are inherited from a parent object, and some properties are NOT inherited. Color and font-size, for instance, ARE inherited, while background, margin, and border (among others) are NOT inherited. For the most part, at this level of CSS use, you will not find this inheritance issue much of a concern. At some point in the future, however, you may come to a point when you have some question about inheritance or lack of inheritance of one property or another; this information is listed at the World Wide Web Consortium at http://www.w3.org/.

42 of 43

8/16/10 2:50 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136092

CSS: Conclusion There's a lot more to CSS than I was able to cover in this brief overview, which was comprised solely of a portion of the CSS1 specification. There is CSS-P, which allows for the absolute, relative, and fixed positioning of elements on an HTML page. There is CSS2, which covers downloadable fonts, pseudo-elements, enhanced table properties, and classes of the pseudoclass, among other things. There are even more versions of CSS in the works, e.g., CSS3 (Version 3.0) which continues in development. Its improved highlights include: vertical text, extensive backgrounds and borders, speech recognition and user interaction. Most web browsers will support CSS3 as it becomes more popular and when more web designers implement the use of CSS3 in their layout design. Here is a tutorial on CSS3. CSS is a vast and rapidly changing field, with ramifications in XML, Dynamic HTML, and other new technologies. Some of CSS has not yet been fully implemented, but, even with the limited CSS that is currently supported and backward-compatible, CSS opens doors to much greater control over your HTML pages than was ever possible in the past. Check here for CSS Validator. Note: If you're using Firefox then you can check if you have any CSS errors by clicking Tools/Error Console/Warnings.

43 of 43

8/16/10 2:50 PM


name

8/30/10 10:22 PM

Book 4: Graphics Book for Weeks 5-6: Graphics

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 4: Graphics Printed by: Donald Siino Date: Monday, 30 August 2010, 10:21 PM

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 1 of 35


name

8/30/10 10:22 PM

Table of Contents 1 Introduction to Images 2 The IMG (Image) Tag 3 Digital Images 4 Image Types: GIF and JPEG 5 GIF and PNG 6 GIF Compression and Transparency 7 JPEG Compression 8 Web Safe Colors - Hex Codes - Named Colors 9 What are Web-Safe Colors? 10 Inside RGB Color Space 11 Basic Web Design: Color 12 Basic Web Design: Designing for the Web 13 Thumbnail images and Gamma Correction - Paint Shop Pro 14 Client-Side Imagemaps 15 Imagemaps: Mapping Shapes on the Coordinate Plane 16 Imagemaps: Deriving Coordinates Manually 17 Imagemaps: Client-Side vs. Server-Side 18 Imagemaps: IMG, MAP, and AREA tags 19 Paul's Video Tutorial - imagemap coding

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 2 of 35


name

8/30/10 10:22 PM

Introduction to Images Reference in Musciano Book: p. 118-151

Frustrated by the visual limitations of browser-rendered text, beginning students always wants to load their web pages with pictures (especially if those pictures wave, throb, or in any other way shimmy, vibrate, or do the Boogaloo); some neophytes go so far as to eliminate regular HTML-formatted text altogether in favor of an all-graphics design in order to distribute pixel-perfect visuals (text, after all, being so MESSY, what with the display differences between the Mac and the PC, not to mention the fact that you can never count on those pesky users having Friz Quadrata or Copperplate 47D or Bembo Demibold Oblique loaded onto their computers when you need them; those users are so INCONSIDERATE! Why CAN'T we just make our web pages out of one gigantic digital picture and be done with it? All the studies say that no one likes to read on their screen anyway, so I say, who NEEDS HTML? Text is so over-rated!). Obviously, these students are neither practical nor rational. The Web is about the distribution of information. TEXT-based information. You must have text. But what is a web page without pictures? Pretty boring looking. Still, pictures must be used with great discretion, as they can substantially increase the time it takes for your web page to download to the user. Long waiting times at your website will pretty much ensure the departure of your intended audience. To get your message out there, you must streamline your designs for maximum download speed and efficiency. A thorough understanding of the technical ins-and-outs of graphics and images, therefore, can make the difference between a beautiful, fast-downloading website that is useful as well as decorative, and a beautiful slug that no one will ever wait to see.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 3 of 35


name

8/30/10 10:22 PM

The IMG (Image) Tag As we discussed in an earlier module, HTML is text-only. Therefore, you can't actually paste images themselves into an HTML page. You need to use a piece of HTML code called the IMG (image) tag to mark where you want your picture to be inserted; you'll use one IMG tag for each picture you want to insert. The IMG tag, then, contains a URL (either absolute or relative) which points to the location on the Internet where the actual picture (image resource) is stored. When a web browser loads an HTML page into a browser window, it reads the HTML code, finds the image resources marked by the IMG tags, and downloads them; it then assembles the text and pictures together and displays them in the browser window. Wherever you place an IMG tag in the flow of HTML text, a picture will be inserted. Again, wherever you want to place a picture into your HTML page, you need to type in an IMG tag to mark where it goes. Tag: IMG Description: Use the IMG tag to indicate where you want to place a picture in an HTML page. The IMG tag must close in XHTML, as displayed below Example: <img src="capitalA.gif" width="54" height="54" />

Obviously, the IMG tag alone is not enough to do the job; you need to use the SRC attribute of the IMG tag to assign an actual picture to the tag. Tag: IMG Attribute: SRC Value: a URL (relative or absolute) which gives the location of the image resource. Description: The SRC attribute of the IMG tag states exactly where the desired picture resource is located on the Internet. Examples: <img src="./graphics/capitalY.gif" /> (relative URL) <img src="./capitalY.gif" /> (relative URL) <img src="capitalY.gif" /> (relative URL) <img src="http:/fog.ccsf.org/capitalA.gif" /> (absolute URL)

NOTE: Examples 2 and 3 above are identical. Many web designers place all of their image files in a folder (see example 1 above), called graphics, on their web server. The IMG tag has two additional attributes which should ALWAYS be used: WIDTH and HEIGHT. These attributes state the width (in pixels) and the height (in pixels) of the digital image in question. Tag: IMG Attributes: WIDTH, HEIGHT Value: integers representing the width/height of the image in pixels. Description: The WIDTH and HEIGHT attributes tell the browser how wide and tall the picture is; this allows the browser to reserve the correct space on the page for the picture. An IMG tag will operate without WIDTH and HEIGHT attributes, but not efficiently. If you forget to put WIDTH and http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 4 of 35


name

8/30/10 10:22 PM

HEIGHT into your IMG tag, the web browser may prevent the display of anything on the HTML page following that IMG tag until the entire picture is finished downloading. Example: <img src="myGif.gif" width="54" height="110" />

(the above code says that myGif.gif is 54 pixels wide and 110 pixels tall) You may resize an image in the browser window, on the fly, by setting the WIDTH and HEIGHT attributes of the IMG tag to values other than the actual width and height of the image. This is not recommended for most pictures, however, as browsers are extremely poor at resizing images on the fly, introducing ugly pixelations, distortions, empty gaps, or other visual flaws into the picture. The only time you'll resize pictures in this manner is when you are putting what are called "spacer" GIFs into an HTML page; because these "spacer" GIFs are just one color (white, black, some other color, or transparent), the browser can resize these flat-color images beautifully whenever and wherever you like. We'll talk about spacer GIFs when we discuss professional tables in a later module. In the meantime, always make sure you know the exact width and height (in pixels) of your image, and set the WIDTH and HEIGHT attributes of your IMG tag accordingly. Here are some examples of on-the-fly image resizing (all examples use the same GIF file): Normal: <img src="capitalY.gif" width="54" height="54" />

Normal Displayed:

Expanded: <img src="capitalY.gif" width="200" height="200" />

Expanded Displayed:

As you can see, browsers do not resize images very gracefully, and, believe it or not, it used to be much MUCH worse! So always state the image's ACTUAL dimensions for WIDTH and HEIGHT in your IMG tag (unless you are using "spacer" GIFs, as mentioned above).

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 5 of 35


name

8/30/10 10:22 PM

Note: Most image editing programs can tell you the width and height dimensions of your image in pixels. In conclusion, the minimum complement of attributes for the IMG tag must include SRC, WIDTH, and HEIGHT. What is a pixel? A pixel is a square or rectangular dot of colored light. Computers use pixels to display visual content to a user; you put enough pixels together, and you have a picture. Pixels are always formed in a square grid, just like graph paper, in rows and columns. If you look very closely at these words you're reading, this very text on your computer monitor, you can probably see how it's composed of little square pixels (if your eyesight is very sharp). Your Mac or Windows user interface is really a constantly changing digital picture which uses thousands upon thousands of pixels in its display. For the Web, digital images must be created with a resolution of 72 pixels per inch. Remember this when making images in Photoshop for web-based delivery. For print, of course, 300 pixels per inch, 600 pixels per inch, and even 1200 pixels per inch resolutions are not uncommon, but images for the Web are always 72 pixels per inch. 72 pixels per inch used to be the standard resolution for computer monitor displays. It was once the case that if you measured one inch of any digital picture on your computer screen with a ruler, you would see (if you had very sharp eyes) 72 pixels strung end-to-end. With changes in monitor technology, however, there is no longer a physical correlation between what you see on your screen and an actual ruler measurement, since pixels can now be any size (just look at your own monitor, where you should be easily able to reset the screen resolution from being 1024 or 800 pixels wide to being only 640 pixels wide, which will change the size of the actual pixels being displayed). Despite this development, the computer itself understands the correlation between pixels and inches, and if you printed out your web picture with its 72 pixels per inch resolution, you would discover exactly 72 pixels per inch on the printout (if you bothered to count). Note: the rest of this page is continued here.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 6 of 35


name

8/30/10 10:22 PM

Digital Images As mentioned earlier, digital images are made of thousands of little squares called pixels. Each pixel can display one color at a time; this color information is stored in one of a number of different ways. In general, there are two parts to a modern digital image: 1) the picture itself, and 2) the palette of colors available to the picture. In the olden days of computing, there was only 1-bit color, which consisted of black and white (or black and gold, or black and green, depending on the color of the monitor). Each pixel could be either black OR white, off (black) or on (white) (no grays). A 1-bit palette (as such), therefore, has only two colors. The picture was made up of these black and white pixels and was usually rather primitive looking. Example:

As computing technology improved, 8-bit color (and the color palette system) was eventually developed. 8-bit color gave a color palette with 256 possible color choices; each pixel of a picture, therefore, used one of those 256 possible colors. Each pixel of the image would be linked, or "indexed", to one of the 256 colors on the palette. This color palette would be stored in the digital image file along with the pixel-based picture information. Example:

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 7 of 35


name

8/30/10 10:22 PM

With this "indexed" color, it is possible to save a picture with an 8-bit (256 colors), a 7-bit (128 colors), a 6-bit (64 colors), a 5-bit (32 colors), a 4-bit (16 colors), a 3-bit (8 colors), a 2-bit (4 colors), or a 1-bit (2 colors) color palette. The lower the bit-depth of color palette you use, the smaller the file size for the final picture will be. Of course, the more colors you have in your color palette, the greater the fidelity your picture will have to the original. Grayscale images use an 8-bit palette of 256 possible shades of gray to color their pictures; again, each pixel in the image is indexed to one of these 256 shades of gray. Believe it or not, 256 shades of gray make for a very finely detailed rendering of a black-and-white photograph. Example:

Of course, color photographs can use a lot more than 256 colors. To fully represent such pictures, 24bit color was developed. 24-bit color, or "millions of colors", takes grayscale indexing a step further. 24-bit color uses the RGB (red-green-blue) color space, which is the basis of the modern computer display. If you take a photograph and make three grayscale renderings of it, one depicting the 256 possible shades of red, one depicting the 256 possible shades of green, and one depicting the 256 possible shades of blue, http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 8 of 35


name

8/30/10 10:22 PM

then combine those three renderings together, you get a picture with very accurate color reproduction utilizing millions of colors. Each pixel in the picture will be one of 256 possible shades of red, 256 possible shades of green, and 256 possible shades of blue. 24-bit color, however, makes digital images with very large file sizes since there is a lot of color information to store for every pixel. Even 8-bit, or 256 color, images can have fairly large file sizes. Large file sizes are not necessarily a problem if one is simply storing digital images on one's hard drive, or pulling digital images from a Photo CD. File transfer speeds over the Internet, however, are often quite slow, and file size becomes a critical issue when creating images for display via the Web. As a consequence, file compression schemes for digital images were developed to deal with this problem. There are two digital image compression schemes which are universally adopted on the Internet: GIF and JPEG. Before we discuss GIF and JPEG compression schemes, however, we should talk about pixel resolution of an image. The density of pixels in an image can also affect image quality, just as the depth of colors in an image can affect image quality. The more pixels per inch you use, the finer the detail and the greater the resolution of the image becomes. For print purposes, pixel resolutions can vary anywhere from 300 to 1200 pixels per inch; again, the more pixels per inch you have, the better looking the image will be when printed out. More pixels per inch mean smoother lines, finer details, and higher image quality; fewer pixels per inch mean more jagged lines, less detail, and lower image quality. The more pixels per inch you have, however, the greater the final file size for your image. At 1200 pixels per inch in 24-bit color, a 1 inch by 1 inch image will take up 4.32MB of storage space; a 5 inch by 7 inch image (an ordinary photographic print size) would then take up over 151MB of storage space! A modem connection to the Internet can only transfer 3-4KB of data per second, which means that a 151MB image would take somewhere between 10.5 and 14 hours to download, an unreasonable amount of time for a single photograph! The universal resolution for web-delivered graphics, however, is 72 pixels per inch, the same pixel resolution that was once standard for computer monitors. Uncompressed 24-bit color images at 72 pixels per inch, however, are still fairly sizeable: a 5 inch by 7 inch photograph at that resolution would still be over 545KB of data uncompressed, requiring several minutes to download over a modem connection. To make graphics-rich websites a practical reality, then, some sort of image compression is required to make the pictures smaller in file size; that's why GIF and JPEG compression schemes are so important on the Internet.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 9 of 35


name

8/30/10 10:22 PM

Image Types: GIF and JPEG There are two primary compression schemes for image files used on the Web today: GIF and JPEG. Both file types are universally understood by all web browsers. Although often used interchangeably for images, GIF compression and JPEG compression are each suitable for very different types of pictures. GIF compression works best with images that have lots of flat color space (no gradations or continuous tones), such as drawings and flat-color graphics.

Suitable GIF:

JPEG compression works best with pictures that are photographic in nature, without sharp edges, and containing lots of graduated, continuous tone color.

Suitable JPEG:

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 10 of 35


name

8/30/10 10:22 PM

About GIF GIF is a LOSS-LESS compression scheme. A loss-less compression scheme means that there is no loss of image information or quality when using this process to save and compress images; the image you save as a GIF is always reproduced identically every time the GIF is displayed. Every pixel is recorded. A GIF is created from an image that has been reduced to 8-bit (256 color) indexed color or less. As mentioned earlier, each reduction in bit-depth for color gives you 1/2 the possible color choices; 7-bit indexed color lets you have 128 possible colors, 6-bit color lets you have 64 possible colors, 5-bit color lets you have 32 possible colors, etc. The smaller the bit-depth of the indexed colors, the smaller your final GIF is going to be. You should always reduce the indexed color bit-depth of your potential GIF to the lowest you can achieve before the image quality begins to deteriorate more than you can tolerate. At some point, as you reduce the number of colors available to the image, you are going to lose image integrity; the bitdepth cut-off point is an aesthetic decision which must be made on a case-by-case basis. When choosing bit-depth, do so with an adaptive palette; perceptual and selective palettes are also fine. The Web palette option only chooses Web-Safe colors, which are OK for some GIFs and not OK for others; this palette limits the possible colors to a very narrow set (we'll talk about web-safe colors a little later). Note: Never use full 8-bit color when making GIFs with adaptive, perceptual, or selective palettes; only use 7-bit palettes (128 colors) or less. This has to do with Windows-based PCs and their built-in 256 color system palette. Windows-based PCs have 20 reserved colors in their color palette (10 at the beginning of the palette and 10 at the end of the palette). If you create GIFs with a full 256 colors in each of their own palettes, Windows machines will sometimes substitute their reserved colors for the first 10 and last 10 colors in those GIFs 8-bit palettes, causing bizarre color substitutions which may ruin your images when they are displayed in web browsers operating under reduced color conditions (256 colors or thousands of colors). A digital image destined for the Web is composed of a grid of pixels at 72 pixels per inch resolution, as you know. When compressing images, GIF compression scans from left to right across each line of pixels; all consecutive pixels which are the same color are stored as one unit of data; this unit of data also includes the position on the indexed color palette for the color for that group of pixels. Each time there is a change of color moving from left to right across a line of pixels, that pixel (or group of pixels) is stored as a separate unit of data. GIF compression is excellent for graphics which rely on flat color space and sharp edges because of the way it stores information. The loss-less compression of the images reproduces the original graphic perfectly, and is great for sharp lines and clean edges. Images with continuous-tone color, like photographs, do not compress efficiently using GIF compression; JPEG compression is a far better choice for photographs (as we will discuss later). That doesn't mean that you can't use GIF compression on photographs, it just means that, usually, JPEG compression is more appropriate. When creating GIFs, make certain that you don't DITHER the image, as this will cause GIF compression to work less efficiently. Dithering is like pointillist painting. Dithering is the process whereby the computer uses a limited http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 11 of 35


name

8/30/10 10:22 PM

number of colors to approximate other, related colors. This is done by taking pixels of color from your limited color palette and patterning them together in some fashion to simulate another color. Because dithering patterns colors together, it breaks up groupings of solid color. Since GIF compression prefers that like-colors be banded together into groups, dithering can cause GIF files to become larger than they would be without dithering.

PNG (Portable Network Graphic) PNG is a bitmapped image format that employs lossless data compression. PNG was created to improve and replace the GIF format, as an image-file format not requiring a patent license. PNG is pronounced "ping". For more information on PNG, go to Wikipedia or the PNG home site.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 12 of 35


name

8/30/10 10:22 PM

GIF Compression and Transparency GIF89a format IS the current standard for GIF compression. The two most important features of GIF89a format are transparency and animation. Animation will be discussed in another module.

Transparency An arbitrary color on the indexed color palette of a GIF may be selected to be transparent; this means that every pixel in the GIF which is assigned to that color (or a certain collection of those pixels) will be transparent, allowing you to see through the transparent areas of the image to the HTML page beneath. This transparency feature is particularly important if you plan on "floating" images on top of background colors or patterns. Invisible "spacer" GIFs can also be created using 3 pixel by 3 pixel images, in which all of the pixels are transparent. Photoshop has an enhanced means of making transparent images which involves the use of layers. In Photoshop, you do not assign a single color globally to be your transparency color. Instead, you create images that are "floating" on a transparent background by removing your background layer. Then, when you SAVE FOR WEB, you can turn the transparency feature on, and set the MATTE color upon which the transparency will be anti-aliased. Newer versions of Paint Shop Pro also allow for the creation of transparent images. What is aliased vs. anti-aliased? Aliased graphics have strong, pixellated edges with no blurring. Anti-aliased graphics have blurred edges to simulate smooth curves. In this case, a picture is worth a thousand words:

Use aliased graphics where you want clean edges against a background. Use anti-aliased graphics when you prefer the illusion of smoothness over sharp clarity. With transparent images, aliased graphics are the most versatile as they can "float" on any color without leaving an undesirable "halo"; anti-aliased graphics, with their blurred, smooth edges blending with the matte color, can only have transparent backgrounds if you know, in advance, the color that they are going to be matted against and sitting upon. Transparency is only available to GIF images; JPEG images do not support this feature.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 13 of 35


name

8/30/10 10:22 PM

JPEG Compression JPEG compression is a "loss-y" compression scheme; this means that actual image data is lost in the compression process, and that the final JPEG image is only an approximation of the original image. Having said this, extremely high-quality JPEGs can be virtually indistinguishable from original source files, although the final file sizes in very high-quality JPEGs can be quite large. The harder you compress an image using JPEG compression, the smaller your final file size will be, but the more your image quality will suffer. Conversely, the less you compress an image using JPEG compression, the larger your final file size will be, and the better your image quality. JPEG compression uses full 24-bit color to create its images, which means that you can retain the entire rainbow of RGB millions-of-colors when creating JPEGs. Unlike GIFs, you do not index JPEGs to a reduced color palette; instead you retain full 24-bit RGB color while compressing your images. JPEG compression reduces final image file size by only sampling some pre-determined percentage of the total pixels in the picture; sampling is done in inverse proportion to the intensity of compression. The harder you compress an image using JPEG compression, the fewer pixels you sample and the greater the loss of image integrity; the less you compress an image, then, the more pixels you sample and the better the final JPEG image quality. When JPEGs are reassembled by a browser or other application for display, an approximation of the colors which should be surrounding each pixel are made, based on the neighboring sampled pixels (which are sampled, I believe, in a hexagonal pattern). This reconstruction of the original image can be very obvious on highly compressed JPEGs, leaving hexagonal artifacts, blotchy colors, and overall low image quality. On the other hand, with high-quality, less-compressed JPEGs, this image reconstruction is virtually undetectable, leaving only a beautiful photograph. The amount of JPEG compression you want to apply to an image will vary from photograph to photograph, and is an aesthetic judgement based on overall file size restrictions for the site, the number of JPEGs and other graphics you want to display simultaneously, and a host of other considerations. When creating JPEGs for the Web, some compromise will have to be reached between perfect image fidelity and a small file size. You will end up having to sacrifice some degree of image quality, but how much to sacrifice will depend entirely on the purpose you intend for the final image. Are you mounting a portfolio of your paintings on the Web? You will need very highquality JPEGs for that purpose, which means that you should never ask a user to download more than one at a time as the file size for each image will be quite large. On the other hand, if you are creating abstract cloud-images, photographs of fog, or mushy pictures without much detail for backgrounds or sidebars, you can get away with much higher compression before image quality deteriorates appreciably. The rule of thumb to follow is that the more detail you need to recognize in the picture, the less you can compress the image. JPEG compression, by its very nature, is not appropriate for graphics with sharp edges, like text, since JPEG compression only approximates the original image when displayed. If you have a photograph which has text or flow-chart lines or fine detail plastered across it, you may be forced to use GIF compression rather than JPEG compression, even though the final image size and color quality may suffer.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 14 of 35


name

8/30/10 10:22 PM

Web Safe Colors/Hex Codes/Named Colors There are two ways to express color in HTML: 1) named colors, and 2) hex codes. Named colors are easy. There are 16 "official" named colors: aqua, gray, navy, silver, black, green, olive, teal, blue, lime, purple, yellow, fuchsia, maroon, red, and white. There are also hundreds of other named colors, all through the spectrum. The problem with named colors is two-fold. Firstly, named colors have not traditionally been consistent in hue from platform to platform and browser to browser, despite official standards. Secondly, these named colors are mostly not "web-safe"; we'll talk about web-safe colors a little later. The alternative to named colors are hex codes. Hex codes express color precisely using the 24-bit RGB color palette, the standard for full-color reproduction on computers. Hex codes are expressed in seven digits, the first digit always being the # (pound) symbol, followed by six numbers representing the desired color. Here are some example hex codes: black: #000000 white: #FFFFFF Why are there LETTERS in some of these hex codes, and what do these numbers and letters represent? Not all counting systems are in Base 10, the decimal counting system that we are accustomed to. Hex codes are written in Base 16, the hexadecimal counting system. Where we are accustomed to these numbers in Base 10: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

Base 16 uses: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, 10

Because Base 16, or hex, rolls over to "10" at 16 rather than 10, we need to add some letters into our numbers in order to make up the difference. This means that "A" is really 10, "B" is really 11, C is really 12, etc, until you get to "10" which is equivalent to our 16. The hex color code, then, represents the millions of colors, 24-bit RGB color palette. Remember that in 24-bit color, there is one 8-bit palette with 256 shades of red, one 8-bit palette with 256 shades of green, and one 8-bit palette with 256 shades of blue; the three palettes are combined to make millions of possible colors. The hex code is really #RRGGBB; the first two numbers represent 256 possible shades of red, the second two numbers represent 256 possible shades of green, and the third two numbers represent 256 possible shades of blue, making the complete 24-bit RGB color spectrum. Because we are counting in Base 16, or hex, however, we only need two digits to represent all the numbers from 0 to 255. The value "FF", then, is equivalent to 255; the number "00" is equivalent to 0, etc. Any color in the millions of colors RGB spectrum can be coded using these hex codes. Only a fraction of these colors, however, are officially "web-safe". http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 15 of 35


name

8/30/10 10:22 PM

Web-safe colors may only use the following digits (in hex): 00, 33, 66, 99, CC, FF. The following randomly selected codes, then, WOULD be web-safe: #3399CC, #6666FF, #9900FF, etc. The following randomly selected hex codes would NOT be web-safe: #3399A5, #1234AB, #DDDDDD, etc. For those that are interested, the decimal equivalents of the web-safe color units are as follows: 00 33 66 99 CC FF

= = = = = =

0 51 102 153 204 255

Notice how these numbers are all multiples of 51! Knowledge of hex-to-decimal equivalents may prove useful if you are not using the most up-to-date software; some older software requires that color codes be decimal ONLY!

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 16 of 35


name

8/30/10 10:22 PM

What are Web-Safe Colors? (And why are they important?) In the early days of the Web, Netscape decided on 216 colors to form the official "web-safe" color palette; this set of colors was subsequently adopted as the official technical standard across the Web. Under reduced color display conditions (monitors using only 256 colors on the Macintosh, or 1000's of colors (High Color or less) on Windows machines), Netscape Communicator and Internet Explorer reverted to this "web-safe" color palette for displaying everything in the browser window, whether graphics, backgrounds, or text. Under reduced color conditions, any color which is not web-safe will change into its closest web-safe color approximation, either by using two web-safe colors dithered together, or by wholesale conversion to a single similar color. Under full 24-bit color conditions (millions of colors), this forced color conversion does not occur. However, many users do not have full 24-bit color monitors, either because they're using laptop computers, have extremely large monitors without adequate VRAM or computing power, or because they're using cellphones or other unusual web-browsing devices; because of this, it may be necessary to design websites using web-safe colors. The web-safe color palette was created by engineers (notice its numerical regularity!), not by graphic designers. As a consequence, it is rich in vivid, primary colors, but lacks subtle earth tones and many so-called "corporate" colors. You won't find paper-shades, taupe, ecru, variations in off-white, or other subdued colors so popular in the print world. The web-safe color palette is the reason that web design has become known for vivid, jewel-tones and bright, garish color combinations. That's not to say that you can't use other, non-web-safe colors in your designs; you must simply use those non-web-safe colors with caution, and test the results under reduced color display conditions on all platforms.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 17 of 35


name

8/30/10 10:22 PM

Inside RGB Color Space How does RGB color space operate? RGB color space is essentially an additive color space. Subtractive colors are the sorts of colors you use with paints and pigments; additive colors are those involved with colors of light. Computer monitors use light to display colors; therefore, RGB color space is additive. When you add more subtractive colors together, you eventually get black; when you add more additive colors together, you eventually get white. With subtractive colors, red and green make brown; with additive colors, red and green make yellow. In RGB color space, add red and green to get yellow, add green and blue to get aqua, add red and blue to get violet, and add red, green, and blue in equal proportions to get shades of gray. The less color you add, the blacker it will be; the more color you add, the whiter it will be. To reduce the saturation of a color, add more of its opposite; for instance, #FF00FF makes a brilliant, saturated shade of violet, whereas #FFCCFF makes a very pastel violet and #996699 makes a medium-toned, unsaturated violet. #CC6699 might make a pinker violet color, whereas #9966CC makes a bluer violet color.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 18 of 35


name

8/30/10 10:22 PM

Basic Web Design: Color We have discussed the technical aspects of color fairly exhaustively, but I want to reiterate the importance of designing using the web-safe color palette. Chances are that some portion of your user base will be viewing your website using a monitor with restricted color space; since this is the case, web-safe color design will be critical for you. Remember: your hex codes must be combinations of FF, CC, 99, 66, 33, or 00 in order to be valid as web-safe colors. Speaking of color, don't forget your color-blind users. A substantial portion of males has some degree of color blindness, which makes certain color combinations unreadable or indistinguishable; red and black in combination is a classic example (it all looks black). Make certain that you are aware of tone value contrasts as well as hue when designing for color-blind users. Testing your designs in grayscale will give you a much clearer (although not completely accurate) idea of what your design will look like to the color-blind. Also consider the experience of reading black text on a white screen: don't you find it somewhat exhausting to the eye? I sure do! Unlike paper, where black on white is highly readable and highly desirable, a CRT monitor emits light; looking at a white screen is, basically, staring into a light bulb! Because it emits light, the contrast on a monitor is 10 times greater than similar contrast on printed media (at least, that's the figure I've heard). Lower contrast colors (black text on a gray background, for instance) make prolonged reading on a monitor screen easier to tolerate. When creating designs where the reading of text is important, don't use white! Use medium-toned, unsaturated background colors with dark, crisp text. Finally, if you use a dark background, be sure that your text and link colors are light, and vice-versa. Good color contrast is very essential to readable web pages!

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 19 of 35


name

8/30/10 10:22 PM

Basic Web Design: Designing for the Web Design involves more than just graphics; it is the entire user experience. Here are a few things to consider. Scrolling is OK, even expected, as long as the user doesn't have to scroll to view navigation elements, splash screens, or anything else that they should be able to view all at once. The most important things, obviously, should appear right at the top. Don't overload your front page with content; users can only take in so much at a time. Make certain that you maintain a clear and obvious focal point for the page, and don't succumb to clutter as so many web designers have. It's all right if users have to click to get more information, as long as they don't have to click too much. Remember that the most important part of your web page is about 100-200 pixels tall, running across the top of the browser window from the left. This is where users look first! That's why advertisements always live in that space, and why people pay money to rent it or buy it. Don't waste that space! Some of my students in the past have filled that space with emptiness or only a pretty picture with no real content. At least stick your name or company name in there, or whatever you're interested in promoting or selling! Maintain a clear navigational structure. There is nothing more annoying than losing your way in a website of any size, small or gargantuan, and having no clear idea of where you are or how to get anyplace else. Remember that you are designing for a non-print media. Flexibility in a visual design is all important! You will never completely control the manner in which text wraps, nor will you always be able to get elements into the exact same positions on every browser. Don't focus on these minutiae, as they will give you nothing but ulcers! Focus only on the things which you can control reliably, and don't worry about the rest. Use designs with strong focal areas which don't require pinpoint positioning. CSS will help you control your designs more effectively, but it is not a miracle cure; it is just an improvement over plain HTML tags alone. Modern HTML, XHTML, and XML rely strongly on CSS for all appearance control! Don't feel obliged to trap users in your website. The Internet was made for surfing, with easy access to and from locations on the Web; if you lock people into your website for any reason ("branding", ignorance, or just plain fear), you may confuse or even infuriate your users. Make sure that it is as easy to EXIT your site as it is to enter it; users can always hit the "Back" button if they want to return to your site.

Final Note Pretty pictures and elegant graphic design are only a small part of a website; visuals only set the stage. The complete design considers the entire user experience, from ease of access to key content and information, to arrangement of content, to navigational structures and site maps, to proper management of expectations regarding wait and delay (a primary component of most web experience). Technology must be harnessed to provide an enjoyable and seamless user experience; in the best sites, the technology is invisible, subservient to the delivery of information, entertainment, news, shopping, or business. The best use of technology gives the illusion of utter simplicity; you have used technology well if users don't even notice it. http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 20 of 35


name

http://insight.ccsf.edu/mod/book/print.php?id=136080

8/30/10 10:22 PM

Page 21 of 35


name

8/30/10 10:22 PM

Paint Shop Pro Tips 1. Download Paint Shop Pro (Version 6.0 - psp60ev.exe) from: ftp://sol.ccsf.org/pub/Graphics. When launched, Paint Shop Pro will look like the following:

2. Creating a thumbnail image: A thumbnail image should be approximately 100 pixels in width and height (plus or minus a few pixels). It can be created in Paint Shop Pro quite easily by the following steps: a. Open the larger image using the menu option, file/open. b. Note the size of the width and height (in pixels) of the image by using the menu option, view/image. For Example, the following shows that the image has a width=150 and a height=149 (in pixels). The file size of the image is shown as 65k.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 22 of 35


name

8/30/10 10:22 PM

c. Using the menu option image/resize, merely change the width to 100 pixels. The height should automatically change, as long as the option 'maintain aspect ratio of' is checked (which is the default). Then click ok and file/save as. That's all there is to it. Here is an example.

Original

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 23 of 35


name

8/30/10 10:22 PM

Thumbnail

d. Sometimes when you use the above steps to create a thumbnail image, the thumbnail image will appear blurry or unclear. You can then use the menu option image/sharpen to produce a clearer image. Then save. When making a thumbnail image of a jpg file, it is sometimes a good idea to first convert the original jpg to a gif by using the menu option file/save as, and then saving it as a gif. Then you can proceed with the above steps to create a thumbnail gif that can be used as a link to the larger jpg file.

3. Cropping: You can eliminate the unwanted outer portion of an image by using the selection icon on the left icon list. This is called cropping. The icon appears as a dotted rectangle and is normally the 6th icon from http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 24 of 35


name

8/30/10 10:22 PM

the top. Open up your image file and click this icon. Move the pointer to the upper left hand part of the image where you wish cropping to begin and drag the pointer over the image until you reach the lower right hand part of the image where cropping will end, thus forming a dotted rectangle when you release the mouse. Then click the menu option edit/copy and then edit/paste as new image. You can then save this cropped image.

4. Gamma Correction: A background image file can be made lighter in contrast and brightness by using what is called gamma correction. This process gives the background image a 'washed-out' look, which is especially desirable for some web pages where you want the content of the web page to stand out more clearly. It can also help for attaining good color contrast and readability of your web page. Open up your image file and use the menu option colors/adjust/gamma correction. The original image will appear on the left and the gamma corrected image next to it on the right. By adjusting the red/blue/green lever, you can view the gamma corrected image on the right as it changes. When satisfied, click ok and then use file/save as, for the new gamma corrected image. Here is an example:

Gamma correction in Photoshop.

5. Paint Shop Pro Tutorials on the Web: http://www.grafx-design.com/psp_tut.html http://psptips.com/

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 25 of 35


name

8/30/10 10:22 PM

Client-Side Imagemaps You already know how to turn images into hyper-references using the A (anchor) tag to mark an IMG tag. Example: <a href="http://www.yahoo.com/"><img src="capitalA.gif" width="54" height="54" border="0" alt="Capital A" /></a> Displayed:

When you wish to have MORE than one link available from a single picture, however, the above code won't work for you; you'll need to create an imagemap. Here is a simple picture which could benefit from becoming an imagemap; notice the two distinct areas which could be clickable:

Here is an example of the above picture used as an imagemap. Again, an imagemap allows you to take an ordinary image and make multiple clickable hyperreferences available to the user from that one image. I'm sure you've seen much more complex examples of imagemaps while surfing the Web. Any number of areas, in a variety of shapes, may be made clickable within the bounds of a single image. For instance, you could take a picture of the state of California, map all of the counties as separate clickable areas, and make each county on the image a hyper-reference to the appropriate county home page. I'm going to show you how to make an imagemap by hand, which is an important skill. However, when constructing complex imagemaps out in the professional world, you may wish to use some sort of software to derive the imagemap for you, saving time and effort. A shareware program can be downloaded from the Web called MapEdit, which can handle imagemap construction for you automatically. MapEdit is offered for Mac, PC, and UNIX platforms. It is available at http://www.boutell.com/mapedit/. Most major WYSIWYG HTML editors, such as Dreamweaver and Adobe GoLive, include some sort of imagemap generating software. But it is much faster to just code the thing entirely by hand rather than to use more sophisticated software. Because of this, it is important to know exactly how to construct imagemaps quickly and efficiently by hand. For Homework Assignment 5, I strongly suggest that you make your imagemap by hand.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 26 of 35


name

8/30/10 10:22 PM

Imagemaps: Mapping Shapes on the Coordinate Plane Before we can get into details of mapping shapes, we must be certain that we are clear regarding basic graphing skills, mapping coordinates on the two-dimensional Cartesian coordinate plane. Here is an example of what is known as the Cartesian coordinate plane:

To define coordinates on the Cartesian coordinate plane, we use the x-axis and the y-axis to determine how far from the origin point we are (the origin point being 0,0 on the diagram, where the x-axis and y-axis meet); points on the x-axis increase in value as we move to the right, while points on the y-axis increase in value as we move up. A point on the coordinate plain is always defined as "x,y", which defines the location of the point in relation to the x-axis and the y-axis. In the diagram, there are two points mapped: "2,3", which is two over on the x-axis and three up on the y-axis; and "4,1", which is four over on the x-axis and one up on the y-axis. On the computer, locations on the coordinate plane are mapped in a slightly different manner. The origin point of the coordinate plane on the computer is always in the upper-left-hand corner of whatever is being scrutinized. If you are determining locations on the computer screen, the origin point is at the upper-left-hand corner of the screen. If you are determining locations on a web browser window, the origin point is at the upper-left-hand corner of the browser window. If you are determining locations on a digital image, the origin point is at the upper-left-hand-corner of the image itself. On the computer, values on the y-axis increase as you move DOWN, not up; this is because the origin point is at the upper-left-hand corner of things. Here is a diagram to make this point clearer (note the very large pixels that I've drawn):

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 27 of 35


name

8/30/10 10:22 PM

As you can see, the origin (0,0) is in the upper-left-hand corner of this representation of a digital image, and marks the first pixel in the image. I have labeled three other points: "4,1" and "3,4" and "0,2" which all mark the "x,y" coordinates of the various pixels on the image. When you are deriving the position and shape of clickable areas for an image, you will be doing so using these pixel-based x,y coordinates. There are only three types of shapes which may be defined as clickable areas in an imagemap: RECT , CIRCLE , and POLY . Eventually, you will be deriving x,y coordinates for these various shapes and coding those coordinates into HTML tags to create clickable imagemaps. Before you can do that, however, we need to look at the type of coordinates required to define each type of shape.

RECT The RECT shape includes both rectangles and squares. It is defined by two points on the digital image: the position of the upper-left-hand corner of the rectangle, and the position of the lowerright-hand corner of the rectangle. Once you've derived the positions of the upper-left-hand corner and lower-right-hand corner of the rectangle, you put the two sets of x,y coordinates together into one unit, separated by commas, like this: x,y,x1 ,y1

On a theoretical image, the coordinates for a RECT with an upper-left-hand corner at "7,7" and a lower-right-hand corner at "71,71" would be: 7,7,71,71

CIRCLE The CIRCLE shape includes perfect circles only; no ellipses, ovoids, or other irregular shapes are permitted. A CIRCLE shape is defined on an image by the position of the center point of the circle, followed by the radius value of the circle, in pixels; remember that the radius of a circle is 1/2 of its diameter, the diameter being the total width of the circle at its widest point (in pixels). For instance, if a circle is 40 pixels wide (in other words, if its diameter is 40 pixels), the radius value for the circle would be 20 (pixels). Once you've figured out the radius value for the circle, the center point x,y coordinate position and the radius value would be combined, separated by commas, like this: x,y,r

On a theoretical image, the coordinates for a CIRCLE with a center point position of "100,50" and a radius value of 25 pixels would be: 100,50,25

POLY The POLY shape includes all polygons, beginning with triangles and increasing in complexity to the most peculiar and irregular shape you can imagine. A POLY shape must have at least three x,y coordinate points defining it (a triangle), but may have as many x,y coordinate points as desired, in any shape, no matter how squiggly or peculiar. POLYs are used to outline irregular and bizarre shapes, such as county lines on state maps, or the picture of the edge of a book on a bookshelf, or http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 28 of 35


name

8/30/10 10:22 PM

cat's eyes, or crumpled tissue paper, or whatever. The POLY shape must have its coordinates defined, in order, around the circumference of the shape. It doesn't matter whether you move clockwise or counter-clockwise around the polygon, just as long as you present the x,y coordinates in order. If you don't do this, you will not get the shape you want, but some ugly mess, as the computer draws the shape from first point to second point to third point, etc. You don't need to repeat the x,y coordinate for the starting point once you get to the last x,y coordinate of the polygon. As with the RECT , you take all of the x,y coordinates for the POLY and combine them, separated by commas, like this: x,y,x1 ,y1 ,... xn ,yn

For a theoretical triangle shape with three x,y coordinates at its corners ("5,10" and "20,30" and "10,0"), the final coordinates would be: 5,10,20,30,10,0

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 29 of 35


name

8/30/10 10:22 PM

Imagemaps: Deriving Coordinates Manually Deriving x,y coordinates for clickable shapes in an image is not difficult; even deriving x,y coordinates to define complex polygons is not difficult, just time consuming. All that you need for deriving x,y coordinates is image editing software, such as Adobe Photoshop or Paint Shop Pro. Once you have opened your image in one of these programs, you will need to perform the following steps: 1. Make certain that your cursor is shaped like a crosshair; this will allow you to position your cursor precisely over the image. In Paint Shop Pro, the crosshair cursor is active when you have chosen the mover tool, which is the second tool from the left on the lower Tool bar. In Adobe Photoshop, the crosshair cursor is active when you have chosen the marquee tool from the Tool palette (the marquee tool allows you to click-and-drag to select a rectangular area of the image for editing, and is the first tool at the upper-left-hand corner of the Tool palette in Photoshop). Note also that in Photoshop, the coordinates have a default in units of inches instead of pixels. So, you need to switch from inches to pixels. A key command to transfer from inchesto pixels in Photoshop is to control click on the measurements ruler and a menu will pop up and you can choose your choice of measurements. 2. Locate the mouse position x,y coordinate readout for the program. In Paint Shop Pro, this readout is located at the lower left hand corner of the screen. In Photoshop, this readout is located in the Info palette [Check that coordinates are set to pixels.] 3. As you roll your mouse cursor around the screen (WITHOUT clicking or click-and-dragging), you will see the x,y coordinate for your cursor in the mouse position readout mentioned in step 2. You will need to align your cursor over the appropriate point of your chosen shape, and write down the x,y coordinate given in the readout. Make sure that you write down the coordinates for later use in your coding of the imagemap.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 30 of 35


name

8/30/10 10:22 PM

Imagemaps: Client-Side vs. Server-Side Before we get into the nitty-gritty of creating client-side imagemaps in HTML, I want to explain the difference between server-side and client-side imagemaps. Years ago, before HTML had embraced imagemaps, there was special software on every web server which ran "server-side" imagemaps. The user would click on an image on a web page attached to one of these server-side imagemaps (using the ISMAP attribute of the IMG tag), which would call the web server software to analyze the precise location on the image where the user clicked, and serve the appropriate HTML page based on the user click. As you can imagine, these server-side imagemaps took precious time away from the web server's other duties (like serving HTML pages), which slowed down already-slow web servers. Starting with HTML 2.0, client-side imagemaps were introduced as a part of the HTML standard. Client-side imagemaps placed all imagemap information into the HTML page, and were run completely by the web browsers, freeing up the web servers for more important operations. Today, all major web browsers understand client-side imagemaps. The only web browser still in common use which does NOT understand client-side imagemaps is Lynx, the text-only browser (which doesn't even understand pictures). Server-side imagemaps are rarely used anymore. Not only are they a drain on the server, but also have a disadvantage that client-side imagemaps do not have. A client-side imagemap allows one to see the URL in the status bar (lower left of screen), when the mouse is over a hot spot. This is not the case for a server-side imagemap.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 31 of 35


name

8/30/10 10:22 PM

Imagemaps: IMG, MAP, and AREA tags It's time to look at the XHTML necessary to create a client-side imagemap. There are two parts to a client-side imagemap: the IMG tag which displays the image on the XHTML page, and the MAP and AREA tags (invisible to the user) which contain all of the imagemap information. The A (anchor) tag is NOT involved in creating a client-side imagemap. Because the actual imagemap information is coded only into MAP and AREA tags, the IMG tag needs to link to the MAP tag and its imagemap information using a special attribute, USEMAP ; I'll talk about the USEMAP attribute and how it works at length in a moment. Imagemap information is coded into XHTML using the MAP and AREA tags, as mentioned earlier. MAP opens and closes around the imagemap information, with one AREA tag for each clickable area on the imagemap. Here is an example of the basic structure (without attributes): <map> <area /> <area /> <area /> </map>

The MAP tag ALWAYS closes after the AREA statements. The MAP tag has one attribute, ID , which is required for the imagemap to operate properly. Tag: MAP Attribute: NAME Value: any valid name (based on the naming rules discussed in earlier modules) Description: the NAME attribute of the MAP tag provides an identifier which the USEMAP attribute of the IMG tag will use to connect itself to the imagemap information in the MAP . Example (abbreviated): <map name="fred"></map> Note: In order for your XHTML pages to validate with the W3C standards, you need to insert an id attribute into your map statement. For example: <map name="fred" id="fred">

The AREA tag has three required attributes: SHAPE , COORDS , and HREF . The HREF attributes are identical to their A (anchor) tag counterparts except for the fact that they work within an imagemap. Tag: AREA Attribute: SHAPE Value: rect , circle , poly Description: sets the shape of the clickable area which the individual AREA tag will define. Each AREA tag in a MAP may be a different SHAPE , or they may all be the same SHAPE . Tag: AREA Attribute: COORDS Value: integer x,y (and r ) coordinates separated by commas; the number of integers required depends entirely on the value of the SHAPE attribute for that AREA tag. Description: the COORDS attribute of the AREA tag defines the x,y (and r ) coordinates for the shape defined by the SHAPE attribute of that particular AREA tag. http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 32 of 35


name

8/30/10 10:22 PM

Tag: AREA Attribute: HREF Value: any URL, relative or absolute Description: the HREF attribute of the AREA tag defines the hyper-reference for that clickable area in the imagemap. Example: <map name="ethel" id="ethel"> <area shape="rect" coords="7,7,71,71" href="destination1.html" /> <area shape="rect" coords="127,28,191,92" href="destination2.html" /> </map>

Once you've encoded your client-side imagemap information into an HTML page using the MAP and AREA tags, you are ready to add your IMG tag to that XHTML page. An IMG tag used as an imagemap is coded identically to a regular IMG tag, with the addition of two attributes: BORDER and USEMAP . Tag: IMG Attribute: BORDER Value: 0 (zero) Description: the BORDER attribute of the IMG tag must be set equal to "0" when that IMG is being used for an imagemap. Because an IMG tag used as an imagemap is considered to be a hyperreference by a web browser, a blue hot-link border will appear around the image (in many browsers) unless the BORDER attribute is set equal to "0" . Imagemaps, by current conventions, should NOT exhibit a blue hot-link border. Tag: IMG Attribute: USEMAP Value: the # (pound) sign followed by the NAME of the MAP tag to connect to, NO SPACES. For instance, if the NAME of the MAP tag desired was "ethel" (as in the example earlier), the value of the USEMAP attribute for the IMG tag would be "#ethel" . Note: this "#thename" syntax follows the convention established with the A (anchor) tag for hyper-referencing ID anchors within an XHTML page. Description: the USEMAP attribute of the IMG tag connects a MAP tag (and attendant AREA tags) to a given IMG tag, making it behave as an imagemap. Example (including MAP and AREA tags): <img src="demoMap.gif" width="200" height="100" alt="Demo Map" border="0" usemap="#ethel" /> <map name="ethel" id="ethel"> <area shape="rect" coords="7,7,71,71" href="destination1.html" /> <area shape="rect" coords="127,28,191,92" href="destination2.html" /> </map>

It does not matter where on the HTML page the MAP and AREA tags are located. Ordinarily, web programmers will place the MAP tag immediately below the appropriate IMG tag, but the MAP tag could equally well be placed at the bottom or top of the XHTML page without affecting performance in any way. Try to place the MAP tag someplace on the page where it won't interfere with the readability of your code. An XHTML page may have MANY different client-side imagemaps on it, as long as each one of the http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 33 of 35


name

8/30/10 10:22 PM

MAP tags involved is named a unique NAME. You may also place a particular imagemap on a page more than once; simply duplicate the IMG tag involved as often as you need, then have all of those IMG tags access the SAME MAP tag. DO NOT have TWO MAP tags of the SAME NAME on a single XHTML page; this is not only pointless, it is forbidden.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 34 of 35


name

8/30/10 10:22 PM

Paul has created a video tutorial for the coding of an imagemap using Photoshop.

http://insight.ccsf.edu/mod/book/print.php?id=136080

Page 35 of 35


name

9/13/10 3:40 PM

Book 5: Multimedia Book for Weeks 7-8:

Multimedia

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 5: Multimedia Printed by: Donald Siino Date: Monday, 13 September 2010, 03:39 PM

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 1 of 20


name

9/13/10 3:40 PM

Table of Contents 1 Creating an Animated Gif 2 Audio Files 3 Video Files 4 Software for Audio and Video 5 Introduction to Java 6 Java Applets 7 Introduction to Frames 8 Inline Frames

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 2 of 20


name

9/13/10 3:40 PM

Reference in Musciano Book: p. 152-160 Creating an Animated Gif Basic Steps for creating an animated gif, using Paint Shop Pro 6.0 1. 2. 3. 4. 5.

Launch Paint Shop Pro 6.0 Run Animation Shop Run Animation Wizard View the Animated Gif Save the Animated Gif

Paint Shop Pro 6.0 can be downloaded as shareware from various sites on the Web. One such site is ftp://sol.ccsf.org/pub/Graphics. You will be given a 30 day trial period to use the software. If you so desire, you can then purchase it from Jasc. Now launch Paint Shop Pro 6.0. Here is an example of the images that I will use in the animation.

Animation Shop is used to create animated gifs. It is contained within Paint Shop Pro and can be run from the file menu of Paint Shop Pro. The animation process will involve concatenating individual gif files, which can be thought of as slides of the animation. For best effect, the gif files should be exactly the same width and height.

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 3 of 20


name

9/13/10 3:40 PM

From the file menu of Animation Shop, select Animation Wizard. Select the desired option for the animation in each step and then click next. The first step of Animation Wizard looks like this.

You will be asked about total dimensions, canvas color, and frame positioning. For the first 3 steps, I http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 4 of 20


name

9/13/10 3:40 PM

normally leave the defaults as is and click next. The fourth step is important and you should decide whether you wish to loop the animation indefinitely or a certain number of times. I generally prefer the latter. In addition, you need to decide how long you want each frame to be displayed, in 1/100's of a second. I generally make this between 30 and 50. The next step involves specifying the images which are to be loaded as frames. Click the 'add image' button to do this. After adding the images, you may move them up or down for the desired sequence and then click next. Then click finish. You will be returned to Animation Shop. Here is an example.

To view the animation, click the view menu option, and then Animation. Usually the first attempt is not quite satisfactory, and you will then need to return to Animation Shop to run the Animation Wizard a time or two more. When you are finally satisfied, then you can save it. Here is an example of the animated gif that I created using Animation Shop. If the image does NOT seem to be animated then right-click your mouse and refresh the page. (Note: it loops 3 times)

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 5 of 20


name

9/13/10 3:40 PM

Audio Files Midi Files: The Musical Instrument Digital Interface (MIDI) protocol has been widely accepted and utilized by musicians and composers since its conception in the 1982/1983 time frame. MIDI data is a very efficient method of representing musical performance information, and this makes MIDI an attractive protocol not only for composers or performers, but also for computer applications which produce sound, such as multimedia presentations or computer games. MIDI data files are extremely small when compared with sampled audio files. MIDI is not a specification for sampled digital audio. Rather, it contains a bank of digitized sounds and control information for replaying the file - similar to an electronic synthesizer. You can find some midi clips at http://www.prs.net/midi.html/.

Wav Files: Wav files are proprietary to Microsoft and IBM and are most commonly used on Windows-based PCs. You can find some wav clips at http://dir.yahoo.com/Computers_and_Internet/Multimedia/Audio/Archives/WAV/.

Mp3 and Mp4 Files: MP3 files are CD quality songs that are compressed down from huge files to much smaller files without any noticeable decrease in sound quality. These songs are small enough to be stored on your computer, downloaded from the Internet and played on your computer using freely available software. MP3 stands for MPEG 1 (Motion Picture Experts Group) Layer 3. It's a digital audio compression format built from over 15 years of psycho-acoustical research. MP3 squishes down sound files 10-15 times smaller than a parent file. And yet that tiny .mp3 file retains most of the perceived audio fidelity by stripping out the waveforms that the human ear doesn't process. Not nearly CD-quality -- do an "a to b" comparison on headphones and you will quickly unsubscribe from that myth -- MP3 is nonetheless a tremendous breakthrough in terms of sound quality for a high compression rate. Culturally and economically, this little file format has thrown open new vistas of commercial possibilities, altered our music listening habits, and brought concerns about piracy violently to the forefront of our attention. MP4 is short for Moving Picture Expert Group-4. First published in 1998, MPEG-4 or MP4 was designed to encompass all the features that were part of earlier releases of MPEG files, and add a few more that would prove helpful with the advancing online technology of the day. As a standardized group of video and perceptual coding formats, MP in general quickly became a hit with the average Internet user. The introduction of MP4 made it possible for the audience to continue growing by providing quicker, faster, and higher quality broadcast media for the average user. So great was the success of MP4 that by 1999, it was considered the gold standard for all types of http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 6 of 20


name

9/13/10 3:40 PM

streaming and broadcast applications online. The functionality of the format was such that programmers were able to easily make use of MP4 on web sites and in various other applications. Businesses found it to be a great sales and marketing tool, and residential users also had a great time viewing, swapping, and even creating their own streaming media in the MP4 format. You should generally indicate the size of the mp3 or mp4 file on your web page, next to the link for it. You can find some mp3 clips at http://dir.yahoo.com/Computers_and_Internet/Multimedia/Audio/Formats/MP3/.

Embedding Audio Clips: Embedding an audio file on a web page means that the viewer's sound controller will be loaded on the page, at the time that the browser loads the page. Midi, wav, and mp3 files can all be embedded on a web page. In Homework 4, if you embed an audio file then you should also provide a link for it. Note that the embed tag has been deprecated and it will not validate for XHTML. Here is an example of an embedded midi file.

Here is the coding of this example: <embed src="beethoven.mid" autostart="false" loop="false" width="20%" height="20" /> autostart="false" - means that the midi file will NOT start playing automatically right after the page is loaded. This is generally a good idea. The viewer must click the start button on the controller for the file to play. loop="false" - means that the midi file will not keep playing continuously after the viewer clicks start. width="20%" - means that the controller will occupy 20% of the viewer's screen width. heigth="20" -means the controller will be 20 pixels high.

You can also embed an audio file using just the object tag. The object tag will validate for XHTML. See the first example on this page. Here is the coding: <object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="200" height="16"> <param name="src" value="jungle.mp3" /> <param name="controller" value="true" /> <param name="autoplay" value="false" /> <param name="autostart" value="0" /> <param name="pluginspage" value="http://www.apple.com/quicktime/download/" /> <object type="audio/x-mpeg" data="jungle.mp3" width="200" height="16"> <param name="src" value="jungle.mp3" /> http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 7 of 20


name

9/13/10 3:40 PM

<param name="controller" value="true" /> <param name="autoplay" value="false" /> <param name="autostart" value="0" /> <param name="pluginurl" value="http://www.apple.com/quicktime/download/" /> </object> </object> Note: classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" is necessary for the audio file to play in an IE controller. IE needs a non-standard value to the valid classid attribute, an identifier to load an associated activeX.

Notes: 1. If you embed an audio file with the embed tag, I suggest that you also provide a link to it. Here is an example of a linked midi file. This will bring up an audio controller outside of the web page, and the midi file will play automatically. 2. A few semesters ago, a student suggested another method combining the object and embed tags for embedding audio files. It works cross browser and cross platform for all audio filetypes. But it doesn't validate for XHTML because of the embed tag. Here is an example.

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 8 of 20


name

9/13/10 3:40 PM

Video Files Mpeg Files: MPEG, which stands for Moving Picture Experts Group, is the name of family of standards used for coding audio-visual information (e.g., movies, video, music) in a digital compressed format. The major advantage of MPEG compared to other video and audio coding formats is that MPEG files are much smaller for the same quality. This is because MPEG uses very sophisticated compression techniques. MPEG file extensions can be .mpg, .mpeg, or .mpe.

Avi Files: AVI stands for Audio Video Interface. AVI is used in Windows operating systems to provide sound and video. It may drop frames to keep the sound playing, thereby allowing the format to work on almost any Windows machine. The file extension for AVI files is .AVI.

Quicktime Files: QuickTime is Apple's award-winning, industry-standard, software architecture for creating, playing and streaming digital media for Mac OS and Windows. The file extension for quicktime files is either .qt or .mov.

WMV Files: Windows Media Video (WMV) is a generic name for the set of video codec technologies developed by Microsoft. It is part of the Windows Media framework. The codecs were originally developed as proprietary codecs for low-bitrate streaming applications. However, in 2003 Microsoft drafted a video codec specification based on its Windows Media Video version 9 codec and submitted it to SMPTE for standardization. The standard was officially approved in March 2006 as SMPTE 421M, thus making the Windows Media Video 9 codec no longer a proprietary technology. Earlier versions of the codec (7 and 8) are still considered proprietary as they fall outside the SMPTE 421M standard. The video stream is often combined with an audio stream of Windows Media Audio and encapsulated in Advanced Systems Format files, carrying the .wmv or .asf file extensions. WMV files are played by players such as MPlayer or Windows Media Player, the latter being only available for Microsoft Windows and Macintosh systems.

NOTES: 1. There are several more video formats on the web that are not listed here. Video clips are fairly large, which is one reason they are not that common on most web sites. 2. You can find some video clips at http://dir.yahoo.com/Entertainment/Movies_and_Film/Multimedia/Video_Clips/. 3. You can use google to search for video and audio clips by entering +audio+video+clips. 4. To save a video clip to disk, right click on the link to the video, and then click 'save target as'.

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 9 of 20


name

9/13/10 3:40 PM

Embedding Video Clips: Embedding a video file on a web page means that the viewer's associated video controller will be loaded onto the page, at the time that the browser loads the page. Here is an example of a web page that contains two embedded videos.

Here is the coding of the first embedded video file, julia.qt: <embed src="julia.qt" height="140" width="160" autostart="false" loop="false" controller="true" /> autostart="false" means that the quicktime file will NOT start playing automatically right after the page is loaded. This is generally a good idea. The viewer must click the start button on the video controller for the file to play. height="140" - means the controller will be 140 pixels high. width="160" - means that the controller will be 160 pixels wide. loop="false" - means that the quicktime file will not keep playing continuously after the viewer clicks start. controller="true" - This adds user controls to the movie.

Notes: 1. If you are going to embed a video file I suggest that you also link to it. This will bring up a video controller outside of the web page, and the video file will play after it is downloaded. Whether your video file is linked or embedded, you should consider indicating the size of the file in parentheses. 2. I found the following code from the web and it worked for <a href="http://fog.ccsf.edu/~srubin/julia.html">embedding a video file</a>. It works cross browser and cross platform. It also validates in XHTML. <br><br> Be sure to replace julia.qt with your video filename. You may need to also change the width and height dimensions so that your video fits inside the controller. <br><br> <object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="160" height="136"> <param name="src" value="julia.qt" /> <param name="autoplay" value="true" /> <embed src="julia.qt" type="image/x-macpaint" pluginspage="http://www.apple.com/quicktime/download" width="160" height="136" autoplay="true" /> </object> <br><br> http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 10 of 20


name

9/13/10 3:40 PM

3. You can also use the Quick Time Object (QTObject) for embedding video files. I have found using this to be superior than using the embed tag because, unlike the embed tag, it works cross browser and cross platform. Here is an example. 4. You can embed an video file using just the object tag. The object tag will validate for XHTML. See the second example on this page.

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 11 of 20


name

9/13/10 3:40 PM

Software for Audio and Video Below are graphical buttons that you can click on, to go to web sites that allow you FREE downloads of audio and video standalone applications, that act as plugins to your browser. You may wish to include these buttons, wherever they are relevant to playing your audio or video clips in Homework 4. Windows Media Player

QuickTime

Plays QuickTime video clips, as well as other audio and video formats.

Plays mpeg, mov, avi, wav, midi, mp3, and qt. Version 11 is the latest version.

RealPlayer

MusicMatch Jukebox

Plays almost any audio format. Can convert an audio cd song to mp3.

Plays RealAudio, RealVideo Enhanced overall quality.

Add-ons for Firefox

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 12 of 20


name

9/13/10 3:40 PM

Introduction to Java What's the difference between JavaScript and Java? Actually, the 2 languages have almost nothing in common except for the name. Although Java is technically an interpreted programming language, it is coded in a similar fashion to C++, with seperate header and class files, compiled together prior to execution. It is powerful enough to write major applications and insert them in a web page as a special object called an "applet." Java has been generating a lot of excitment because of its unique ability to run the same program on IBM, Mac, and Unix computers. Java is not considered an easy-to-use language for non-programmers. Javascript is much simpler to use than Java. With Javascript, if I want check a form for errors, I just type an ifthen statement at the top of my page. No compiling, no applets, just a simple sequence.

Java Applets A Java applet is a program written in the JavaTM programming language that can be included in an HTML page, much in the same way an image is included. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 13 of 20


name

9/13/10 3:40 PM

The Applet Tag For a java applet to work on a web page, it must already have been compiled. A compiled java applet normally has a file extension of .class Here is an example of a simple applet tag: <applet code="myApplet.class" width="100" height="140"> </applet>

This tells the viewer or browser to load the applet whose compiled code is in myApplet.class (in the same directory as the current HTML document), and to set the initial size of the applet to 100 pixels wide and 140 pixels high. Here's a more complex example of an APPLET tag: <applet code="flame.class" width="250" height="110"> <param name="text" value="Bungle+in+the+Jungle" /> <param name="link" value="http://javaboutique.com" /> </applet>

This tells the viewer or browser to load the applet whose compiled code is flame.class. The first param statement sets the applet's "text" attribute (which customizes the text this applet displays) to be "Bungle+in+the+Jungle". A second param statement will allow the applet to also act as a link, if one clicks the text at the bottom of the applet. If the page is viewed by a browser that can't execute Java applets, then the browser will ignore the APPLET and PARAM tags, displaying only the HTML between the <param /> and </applet> tags (the alternate HTML). Here's the result of putting the above example in your XHTML file. Here's the complete syntax for the Applet tag.

The Object Tag Note that the applet tag is valid for Transitional XHTML, but not for Strict XHTML because the applet tag has been deprecated. Instead you can use the object tag, which is valid for Transitional and Strict XHTML. See the third example on this page, which uses the object tag. For example: <!-- first object tag is for Firefox --> <object classid="java:flame.class" type="application/x-java-applet" height="200" width="200"> <param name="text" value="Bungle+in+the+Jungle" /> <!-- 2nd object tag is for IE --> <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" height="200" width="200"> <param name="code" value="flame" /> http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 14 of 20


name

9/13/10 3:40 PM

<param name="text" value="Bungle+in+the+Jungle" /> </object> </object> The classid attribute identifies which version of Java Plug-in to use. For Firefox - classid="java:classname.class" (where classname.class should be replaced by the actual name, e.g.,

classid="java:flame.class")

For IE - classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"

(always use this classid for IE, but note that it may not display the applet in some versions/platforms for IE)

Note: I suggest that you upload your class file and all associated folders and files directly into the directory that contains your hw5.html file. For more information about the object tag for java applets, see the following links: http://www.w3schools.com/tags/tag_object.asp http://www.veiled-chameleon.com/weblog/archives/000004.html http://java.sun.com/j2se/1.5.0/docs/guide/plugin/developer_guide/using_tags.html#object

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 15 of 20


name

9/13/10 3:40 PM

Introduction to Frames What Is a Frame? A frame is a division of a browser window which displays a distinct HTML page. A browser window can be divided into multiple frames, with each frame displaying a different HTML page. In this example, I have taken a screenshot of a sample frame page. This frame page is actually FOUR HTML pages: one HTML page for the frame document, and three other HTML pages, one page per frame. Frame pages themselves display NO visible content; they merely lay out the frames, determining their dimensions and default pages. All the visible content is displayed with regular HTML pages, one page per frame.

What Are Frames Used For? Frames are used to help users easily find their way through tangled or difficult-to-navigate content (i.e. multiple chapters in an online book with numerous hyper-referenced footnotes). Frames provide a means for a persistent navigation strip to be available to a user at all times, while providing additional areas for display of content, whether primary or ancillary. Having said this, it is easiest to explain frames by showing you an example. Here, I have created a demonstration piece (Frames Example) which exhibits primary frame characteristics. Frames can be useful when providing for some sort of persistent element, such as a navigation strip (as seen in the above example) or a flash/shockwave movie. Here is an example of a web page using frames. That said, frames are much maligned, by developers and users alike. Although frames sites have failings, many of these failings are caused by poor design, not by the frames themselves.

Why Do People Hate Frames? Sub-pages within a frameset may not be bookmarked, a feature which many users find annoying. This is probably the number one complaint with users. Due to the multiplicity of pages involved in a single frame site, the number of simultaneous hits received by a server for the first frame page is greatly increased, causing problems for sites with heavy usage. With a three-frame frames page, for instance, the server receives four hits, instead of one hit as with a regular HTML page, quadrupling traffic for that first page; subsequent pages called from within the frameset, of course, behave normally. This is only a problem with high-traffic web sites. Search engines tend to catalog sub-pages within a frame site, bringing up sub-pages for users without a frameset or any context. There is a workaround for this problem, but it is an awkward one. Many inexperienced web programmers (and some experienced ones) use frames to "keep" or "trap" http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 16 of 20


name

9/13/10 3:40 PM

their users within the confines of their frameset; this has become one of the biggest evils in contemporary web design. Marketing people, especially, wish to "brand" the web within a frame containing their company logo, forcing users to surf within this restricted web browser window space from which there is no escape. As users surf the web, they encounter more and more of these "branding" framesets, which they cannot erase or remove, until they have accumulated so many framesets in their browser window that the usable space left for browsing is the size of a postage stamp, forcing them to quit out of their browser altogether. This practice has become such a problem that many major web services will refuse to list or link to your web site if you use "branding" or unerasable framesets. Any link which leads out of your web site MUST erase any framesets in use.

Conclusion Frames are part of the official HTML specifications. Frames have several technical drawbacks, however, and may be easily misused. One should use frames only when absolutely necessary and avoid using them whenever possible. I have observed that frames are rarely used anymore for developing web pages and with that in mind, I have omitted a full discussion of frames from this course except for a discussion of internal frames.

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 17 of 20


name

9/13/10 3:40 PM

Inline Frames An inline frame (iframe) cannot be viewed on all browsers. Internet Explorer and Firefox are two of the browsers that handle inline frames correctly. The <iframe> tag allows you to create a frame that can appear anywhere within a standard html document. This can be useful for utilizing page sidebars and for highlighting related external elements. You can target links to open other pages in the iframe. It is very simple to code and there is no need for a separate page containing the frameset tag. On the other hand, you must create a separate html document to contain the information that will be placed in the inline frame.

Here is an example of an inline frame: Hello

Here is the code for the above example: <iframe src="ifra.html" width="20%" height="70" align="left" name="ifra"></iframe>

Attribute: src Description: The src attribute is used to define the source html document for the inline frame. From Example: src="ifra.html"

Attribute: width Description: The width attribute allows you to define the width of the frame, as either a pixel value or as a percentage of the browser window. From Example: width="20%"

Attribute: height Description: The height attribute allows you to define the height of the frame, as either a pixel value or as a percentage of the browser window. From Example: height="70"

Attribute: align Description: The align tag allow you to set the justification for the frame within the core html page, http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 18 of 20


name

9/13/10 3:40 PM

just as if you were aligning an image. From Example: align="left"

Attribute: name Description: The name attribute allows you to name the frame. This name allows you to target elements, such as a new page or an image, in the <a href....> statement on the current page. From Example: name="ifra"

Here is another example of an inline frame: Isn't this interesting!

Here is the code for the above example: <iframe src="ifra1.html" width="300" height="150" align="right" name="ifr"></iframe> Now let's put an image in that inline frame by clicking here. Here is the code for the above link: <a href="croc.jpg" target="ifr">clicking here</a> Note that target="ifr" is needed to direct croc.jpg into the iframe, whose name attribute is ifr. Here is an example that uses an inline frame with the new attribute 'frameborder'. The value of 0 indicates no border.

Hello there!

Here is the html code for it: <iframe src="ifra.html" frameborder="0" width="200" height="80" name="cwindow"></iframe>

Note: For browsers that do not support inline frames, you should place text after the http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 19 of 20


name

9/13/10 3:40 PM

iframe tag, but before the /iframe tag, to tell the viewer that their browser does not support inline frames. Example: <iframe src="ifra1.html" width="300" height="150" align="right" name="ifr"> <!-- Here's what would show using a browser that does not support inline frames --> Your browser does not support inline frames </iframe>

http://insight.ccsf.edu/mod/book/print.php?id=136086

Page 20 of 20


name

10/11/10 10:01 PM

Book 6: Cascading Style Sheets II Book for Week 11:

Cascading Style Sheets II

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 6: Cascading Style Sheets II Printed by: Donald Siino Date: Monday, 11 October 2010, 10:01 PM

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 1 of 22


name

10/11/10 10:01 PM

Table of Contents 1 Introduction to CSS-P 2 CSS-P - Basic Positioning 3 CSS-P - The width Property 4 CSS-P - The z-index Property 5 CSS-P - Making a Colored DIV Box 6 CSS-P - Child DIV Tags 7 CSS-P - Hints and Closing Words

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 2 of 22


name

10/11/10 10:01 PM

Introduction to CSS-P CSS-P (or Cascading Style Sheets Positioning, a part of the unevenly implemented CSS2 standards) allows the web programmer to position HTML-formatted resources anywhere they like on a web page. Here is an example of an HTML page which consists entirely of CSS-P positioned elements. As you can see, CSS-P provides a Quark-like or PageMaker-like paradigm for laying out HTML content, replacing tables as the primary means for page layout in HTML. Unfortunately, due to some serious bugs and uneven implementation of the standards in Firefox, Internet Explorer, and other browsers, the day when web programmers can entirely replace tablesbased layout with CSS-P-based layout is probably still a few years away. In the meantime, CSS-P provides programmers with a means for creating application-like screens from positioned "layers" which, in combination with JavaScript, can be used to create simple "dynamic" HTML content (or DHTML). Sometimes Firefox and Internet Explorer browsers fail to generate scrollbars on an entirely CSS-Pbased HTML page which scrolls beyond the bounds of the browser window. Therefore, you must use CSS-P only within the "splash" region of your HTML page (within the first 300-400 pixels in height, and 500-700 pixels in width) so that the user won't have to scroll to see the CSS-P-based content. Due to difficulties in combining positioned and non-positioned elements reliably, you should probably also use CSS-P only by itself, not in combination with regular HTML on a page. These are not hard-and-fast rules, of course, but merely suggestions for avoiding technical difficulties. In the following sections, I will show you how to use CSS-P effectively. I will not be explaining the entirety of the standards, only those portions which work reliably cross-browser and cross-platform. For more information on CSS-P as it is currently implemented, you may wish to read pertinent sections of "Dynamic HTML: The Definitive Reference" by Danny Goodman.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 3 of 22


name

10/11/10 10:01 PM

CSS-P - Basic Positioning Only one type of HTML tag should normally be positioned: the DIV tag. This sounds very restrictive, but it's really not, because ANY type of HTML content may be placed WITHIN the DIV tag which we're positioning. So the positioned DIV tag will ONLY have CSS-P properties assigned to it; you won't be assigning regular text-formatting CSS properties to a DIV tag. Text-formatting properties will only be assigned to the P tag, the heading tags, etc, as usual. The DIV tag was originally created to mark a section division within a larger HTML page, but it has been co-opted by CSS-P to mark positionable elements. As I mentioned earlier, you may put any sort of HTML content you like within a positioned DIV tag. In the future, you will be able to cut out the middleman and assign CSS-P properties directly to ANY HTML tag, positioning that tag. As long as we are supporting some older browsers, however, you should only assign CSS-P properties to DIV tags. Interestingly IE does support CSS-P properties on most HTML tags and so does Firefox to a lesser extent. But again, I strongly urge you to use CSS-P with ONLY the DIV tag. In the following example, we are going to use a DIV tag to position an IMG tag. Example (abbreviated): <div> <img src="capitalA.gif" width="54" height="54" /> </div>

The DIV tag requires one attribute: ID. This ID will be set to a unique identifying name, and assigned appropriate CSS-P properties in EITHER a linked or embedded style sheet. Note: To ensure cross-browser compatibility, you MUST use an ID to assign CSS-P properties to a DIV tag. Tag: DIV Attribute: ID Value: any valid, unique name. Example (abbreviated): <div id="fred"> <img src="capitalA.gif" width="54" height="54" /> </div>

In the linked or embedded style sheet, then, you would create the declaration for the fred ID of our example, and assign it essential CSS-P properties. When using absolute positioning (the only type of positioning addressed in this tutorial), elements are positioned from THEIR upper-left-hand corner in relation to the upper-left-hand corner of the web page. If we wanted to position fred's upper-left-hand corner at 100,30 on the web page, we would http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 4 of 22


name

10/11/10 10:01 PM

need to set three CSS properties: position, left, and top. The position property will always be set to absolute. The left property represents the x-coordinate value, and the top property represents the ycoordinate value; these properties are ALWAYS set using pixel values. Example (abbreviated): #fred { position:absolute; left:100px; top:30px; }

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; } </style> </head> <body> <div id="fred"> <img src="capitalA.gif" width="54" height="54" /> </div> </body> </html>

Here is the above example displayed. In the above example, fred's upper-left-hand corner is positioned 100 pixels from the left, and 30 pixels from the top. Again, there are a minimum of THREE essential CSS-P properties required to position an element: position, left, and top. The position property declares what sort of positioning we're talking about (there are several different types); the left property gives the x-coordinate (in pixels) for the positioned element; the top property gives the y-coordinate (in pixels) for the positioned element.

Required CSS-P Properties Property: position Values: relative, absolute, fixed Example: position:absolute;

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 5 of 22


name

10/11/10 10:01 PM

Relative positioning is hard to control, imperfectly implemented, and rarely used. Here is a good example using absolute and relative positioning, by Paul Strader. Fixed positioning removes an element from the flow of HTML code and "fixes" that element in the web browser window so that other elements on an HTML page scroll up and down while the "fixed" element remains stationary, stuck in place. Fixed positioning is implemented in most of the current browsers. Absolute positioning is the most commonly used type of positioning, and the sole type of positioning addressed in this tutorial. An absolutely positioned element is removed from the regular flow of HTML code and positioned in relation to the upper-left-hand corner of the web page. In this tutorial (and in CSS-P for most purposes), the position property will ALWAYS be set to absolute. Property: left Values: integer-based pixel values (i.e. 10px, 172px, 59px, etc) Description: sets the x-coordinate for the positioned element, in pixels. Example: left:10px; Property: top Values: integer-based pixel values (i.e. 10px, 172px, 59px, etc) Description: sets the y-coordinate for positioned element, in pixels. Example: top:25px; ALWAYS define left and top properties using integer pixel-based values. Again, position, left, and top properties are all REQUIRED when using CSS-P. You may define as many positioned DIV tags on an HTML page as you wish, each with its own unique ID and CSS ID declaration.

Additional Example Obviously, you may position more than just images in this manner; you may position ANYTHING. In the following example, I have positioned a simple table. Example (abbreviated): <div id="fred"> <table width="200" border="1"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </table> </div> http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 6 of 22


name

10/11/10 10:01 PM

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; } </style> </head> <body> <div id="fred" border="1"> <table width="200"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </table> </div> </body> </html>

Here is the above example displayed.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 7 of 22


name

10/11/10 10:01 PM

Positioning Text: The width Property You can position paragraphs of text in the same way that you position images, using a positioned DIV tag. Example (abbreviated): <div id="fred"> <p>Here is some text. It is not very exciting text, but it is long. Long, long text. It goes on and on and on. Why, look at all this text! I wonder if it will ever say anything interesting? No, I think not! But it sure is long!</p> <p>Here is another paragraph of text. This one is short.</p> </div> Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; } </style> </head> <body>

<div id="fred"> <p>Here is some text. It is not very exciting text, but it is long. Long, long text. It goes on and on and on. Why, look at all this text! I wonder if it will ever say anything interesting? No, I think not! But it sure is long!</p> <p>Here is another paragraph of text. This one is short.</p> </div> </body> </html> Here is the above example displayed. Notice how the text wraps to the edge of the browser window in the displayed example? If you want to control the width of the text column, you need to set the width property of the positioned DIV element, in addition to the position, left, and top properties.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 8 of 22


name

10/11/10 10:01 PM

Property: width Values: any integer-based pixel value (100px, 250px, etc) Description: The width property sets the width of a positioned element. Example: width:250px; Example (abbreviated): #fred { position:absolute; left:100px; top:30px; width:250px; }

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; width:250px; } </style> </head> <body>

<div id="fred"> <p>Here is some text. It is not very exciting text, but it is long. Long, long text. It goes on and on and on. Why, look at all this text! I wonder if it will ever say anything interesting? No, I think not! But it sure is long!</p> <p>Here is another paragraph of text. This one is short.</p> </div> </body> </html> Here is the above example displayed. You get the idea. To restrict the width of a positioned DIV which contains something like paragraphs of text, you will need to set the width property in the ID for the positioned DIV in the style sheet.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 9 of 22


name

10/11/10 10:01 PM

When Elements Overlap: The z-index Property When two positioned elements overlap, how do you tell the browser which element goes in front? Just as you use the left property to set the x-axis (left to right) value, and the top property to set the y-axis (up and down) value, you need to use the z-index property to set the z-axis (forward and back) value in this flattened three-dimensional space; z-index tells the browser which element goes in front and which element goes behind. Property: z-index Values: 0 (zero) or any integer; (negative values are permitted). Example: z-index:10; The higher the z-index value is, the farther in front an element becomes; the lower the z-index value is, the farther in back an element becomes. You may not use numbers with decimal places. In the following example, I have two positioned DIV tags, fred (which contains the letter A graphic) and martha (which contains the letter B graphic). I have set fred's z-index to 10, and martha's z-index to 20; martha, therefore, is in front of fred. Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; z-index:10; } #martha { position:absolute; left:120px; top:45px; z-index:20; } </style> </head> <body> <div id="fred"> <img src="capitalA.gif" width="54" height="54" /> </div> <div id="martha"> <img src="capitalB.gif" width="54" height="54" /> </div> http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 10 of 22


name

10/11/10 10:01 PM

</body> </html>

Here is the above example displayed. In the next example, I have the same layout, but this time I have set fred's z-index to 100, bringing it in front of martha. Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; z-index:100; } #martha { position:absolute; left:120px; top:45px; z-index:20; } </style> </head> <body> <div id="fred"> <img src="capitalA.gif" width="54" height="54" /> </div> <div id="martha"> <img src="capitalB.gif" width="54" height="54" /> </div> </body> </html>

Here is the above example displayed. Again, higher z-index values go in front, lower z-index values go in back. If NO z-index value is set, or BOTH z-index values are identical, then whichever DIV element comes LATEST on the HTML page goes in front. In the following example, fred and martha have both been set to a z-index of 10. Because martha comes later in the HTML code than fred, she ends up being placed in front. http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 11 of 22


name

10/11/10 10:01 PM

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; z-index:10; } #martha { position:absolute; left:120px; top:45px; z-index:10; } </style> </head> <body> <div id="fred"> <img src="capitalA.gif" width="54" height="54" /> </div> <div id="martha"> <img src="capitalB.gif" width="54" height="54" /> </div> </body> </html>

Here is the above example displayed. Some designers start with their first positioned element being at a z-index of at least 10. That way, if they change their mind about the design and need to position something BEHIND that element, they still have some z-index values left! Some designers also increment z-index by multiples of 10 (10, 20, 30, 40, etc), so that they have some z-index values BETWEEN various elements, in case they need to insert something else later. You can also place an image underneath some text by applying a z-index of -1 to the image. Here is an example.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 12 of 22


name

10/11/10 10:01 PM

Making a Colored DIV Box You can turn a positioned DIV tag into a colored box. This feature is particularly useful when creating application "screens" for DHTML purposes. It can also be used, to a much lesser extent, as a means of creating low-weight design elements without GIFs. There is only one real way to create these colored boxes which are supported by ALL of the browsers properly. First, you must create a DIV tag on your page and position it, as usual. In this case, however, the DIV tag will be empty (although it doesn't have to be, as we'll see in later sections). Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; } </style> </head> <body> <div id="fred"> </div> </body> </html>

Now, obviously, this isn't complete. To create the box, you must define BOTH the width and height properties in your CSS declaration using pixel values; this will give dimension to your box. Property: width Values: any positive integer-based pixel value (100px, 250px, etc). Description: defines the width of a positioned element. Property: height Values: any positive integer-based pixel value (100px, 250px, etc). Description: defines the height of a positioned element. Example (abbreviated): #fred { position:absolute; left:100px; top:30px; width:100px; http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 13 of 22


name

10/11/10 10:01 PM

}

height:100px;

In addition to width and height, you must ALSO set background-color, to give color to the box. Property: background-color Values: any hex code color value (#CC66CC, #FFCCCC, etc) Description: defines background color for a positioned element in IE or Firefox. Example (abbreviated): #fred { position:absolute; left:100px; top:30px; width:100px; height:100px; background-color:#CC99CC; }

Last, but not least, you MUST set the border property for the positioned element. The border property ensures that the box will be solid and opaque on all browsers. Without the border property, the box will not be cross-browser compatible. The border MUST be solid, 1px wide, and the SAME color as the background color; we'll talk more about this in a moment. Property: border Values: border type (solid), width of border (1px), hex code for color of border (same as background color); each of these values MUST be separated by one space, no commas! Example: border:solid 1px #CC99CC; Example (abbreviated): #fred { position:absolute; left:100px; top:30px; width:100px; height:100px; background-color:#996699; border:solid 1px #996699; }

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 14 of 22


name

10/11/10 10:01 PM

}

position:absolute; left:100px; top:30px; width:100px; height:100px; background-color:#996699; border:solid 1px #996699;

</style> </head> <body> <div id="fred"> </div> </body> </html>

Here is the above example displayed. The border MUST be the same color as the background color; this is due to flaws in CSS implementation in older Netscape browsers. Just as with regular CSS-P positioned elements, you may use the z-index property to indicate which DIV box goes in front. In the following example, I have positioned fred in front of martha. Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #fred { position:absolute; left:100px; top:30px; z-index:20; width:100px; height:100px; background-color:#996699; border:solid 1px #996699; } #martha { position:absolute; left:150px; top:100px; z-index:10; width:100px; height:50px; background-color:#336699; border:solid 1px #336699; http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 15 of 22


name

10/11/10 10:01 PM

} </style> </head> <body> <div id="fred"> </div> <div id="martha"> </div> </body> </html>

Here is the above example displayed. Again, the procedure that I have outlined above is the one and only way you can make boxes out of DIV tags which will be respected on all browsers on all platforms. These sorts of boxes are used frequently in DHTML.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 16 of 22


name

10/11/10 10:01 PM

Positioning Within a Colored DIV Box: Child DIV Tags Putting text, images, or other HTML content directly into a positioned and colored DIV box produces results which are inconsistent from browser to browser and not entirely satisfying, aesthetically. It is impossible to control the distance between the content and the edge of the DIV box consistently when the content is plopped directly into a colored and positioned DIV box. To produce consistent appearance and to control properly the distance between the edge of positioned content and the edge of a DIV box, one must put HTML content into positioned DIV tags which are NESTED INSIDE the positioned, colored DIV box. Example (abbreviated): <div id="parentDiv"> <div id="childDiv"> <p>Here is some text. And some more text. And so on and so on and so on.</p> </div> </div>

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #parentDiv { position:absolute; left:100px; top:30px; width:200px; height:200px; background-color:#CC99CC; border:solid 1px #CC99CC; } #childDiv { position:absolute; left:10px; top:10px; width:180px; } </style> </head> <body> <div id="parentDiv"> <div id="childDiv"> <p>Here is some text. And some more text. And so on and so on and so on.</p> </div> </div> http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 17 of 22


name

10/11/10 10:01 PM

</body> </html>

Here is the above example displayed. In the above example, you can see that I have created a DIV box named "parentDiv" which is 200x200. Inside the "parentDiv" DIV tag, I have nested another DIV tag called "childDiv" which contains a paragraph of text. "childDiv" has been set to be 180 pixels wide. You will notice that the "childDiv" DIV tag's positioning is set at 10,10. Child nested elements are positioned in relation to the PARENT element, NOT to the web page as a whole. Therefore, "childDiv" is 10 pixels from the left and 10 pixels from the top of the PARENT element's upper-lefthand corner. The "childDiv" DIV tag has been set to be 180 pixels wide. Since it has been positioned 10 pixels from the left of the parent element, and the parent element is 200 pixels wide, I want to create an even "margin" (it's not actually a CSS margin, but, rather, an artificial margin that we've created); to do this, I have made the "childDiv" 180 pixels wide, which wraps the text 10 pixels from the right edge of the parent box. The point here is that, because padding, border, and margin properties do not work consistently crossbrowser in CSS-P, I have had to create a fake margin by positioning a child element absolutely within an absolutely positioned parent element. By making parent/child positioned elements in this fashion, you actually end up saving yourself trouble when you start moving into DHTML coding. Thus, if you write only to minimally formatted positioned child elements within a larger parent DIV box, the parent DIV box itself does NOT lose it's appearance characteristics and you can reduce the negative effects of this irritating bug. If I were to then move "parentDiv", the "childDiv" DIV tag's positioning information would NOT have to be changed, but would move with the parent element automatically. Example (abbreviated): #parentDiv { position:absolute; left:200px; top:100px; width:200px; height:200px; background-color:#CC99CC; border:solid 1px #CC99CC; } #childDiv { position:absolute; left:10px; top:10px; width:180px; }

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 18 of 22


name

10/11/10 10:01 PM

Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> #parentDiv { position:absolute; left:200px; top:100px; width:200px; height:200px; background-color:#CC99CC; border:solid 1px #CC99CC; } #childDiv { position:absolute; left:10px; top:10px; width:180px; } </style> </head> <body> <div id="parentDiv"> <div id="childDiv"> <p>Here is some text. And some more text. And so on and so on and so on.</p> </div> </div> </body> </html>

Here is the above example displayed. Again, notice that although the "parentDiv" positioning information has changed, moving the entire element to another location on the page, the "childDiv" positioning information has NOT changed. This feature allows you to move the parent element around on different HTML pages without having to recalculate the child positions, as well. You can position more than one element within a parent DIV tag. In fact, you can position as many elements as you like within a parent DIV tag. Example (in context using an embedded style sheet): <html> <head> <title>Example CSS-P Page</title> <style type="text/css"> http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 19 of 22


name

10/11/10 10:01 PM

/* parent DIV tag */ #donaldDuck { position:absolute; left:30px; top:75px; width:300px; height:200px; background-color:#CC99CC; border:solid 1px #CC99CC; } /* child DIV tags */ #huey { position:absolute; left:10px; top:10px; } #dewey { position:absolute; left:90px; top:20px; } #louie { position:absolute; left:50px; top:90px; width:200px; } </style> </head> <body> <div id="donaldDuck"> <div id="huey"> <img src="capitalA.gif" width="54" height="54" /> </div> <div id="dewey"> <img src="capitalB.gif" width="54" height="54" /> </div> <div id="louie"> <p>Here is some text. And some more text. And so on and so on and so on.</p> </div> </div> </body> </html>

Here is the above example displayed.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 20 of 22


name

10/11/10 10:01 PM

Within a parent DIV box in the above example, I have positioned three child elements: two images and a paragraph of text. This feature is extremely useful for creating a complex element, such as a nav bar, which has many component pieces which need to retain consistent positioning in relation to one another, but which, as a whole, you might want to position at different locations on different pages. If you didn't have this parent/child positioning, you would have to recalculate the positions of ALL of the various elements when you moved your navbar; this way, you only have to move the parent element, and all of the child elements follow suit. When positioning parent/child elements, there are only a few rules to keep in mind: 1. The parent DIV box MUST be LARGER than the child elements positioned within it. In other words, all of the child elements MUST fit COMPLETELY within the parent DIV box. Again, you must do this in order to ensure cross-browser compatibility; the browsers don't handle overflow of content in a consistent manner. 2. You can NOT nest DIV tags more than ONE level deep! In other words, you can't have a child positioned element within a child element; this is because the browsers handle "tertiary" nestings in a mutually incompatible and inconsistent manner. As you can see, the restrictions on this sort of CSS-P can make it somewhat difficult to use for general purpose web page layout. We are rapidly moving into more advanced concerns as we brush the edge of DHTML. In DHTML work, this sort of construction is used very frequently, especially for nav bars and application interface elements.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 21 of 22


name

10/11/10 10:01 PM

CSS-P - Hints and Closing Words Although I have only used embedded style sheets to demonstrate CSS-P in this tutorial, I could equally well have used LINKED style sheets, so that I could easily reuse common positioned elements from HTML page to HTML page. Even though most current browsers will allow CSS-P within inline styles, it is suggested to usually avoid it. I was curious how a page using CSS-P would display if I used absolute positioning on regular HTML tags, instead of only on div tags. Here is a page, using regular HTML tags. In IE, it displays almost exactly the same as my sample page using only div tags for CSS-P; while in Firefox, you should notice that there is a slight problem with the spacing after the header and a problem with the positioning for the links at the bottom of the page.

http://insight.ccsf.edu/mod/book/print.php?id=136098

Page 22 of 22


name

10/24/10 6:34 PM

Book 7: Forms Book for Week 12:

Forms

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 7: Forms Printed by: Donald Siino Date: Sunday, 24 October 2010, 06:34 PM

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 1 of 33


name

10/24/10 6:34 PM

Table of Contents 1 Introduction to Forms 2 The FORM Tag and Attributes 3 The INPUT Tag: Radio Buttons, Checkboxes, and Submit Buttons 4 The METHOD Attribute of the FORM Tag 5 The INPUT Tag: TEXT and PASSWORD 6 The INPUT Tag: the CHECKED Attribute and the Reset Button 7 The INPUT Tag: IMAGE and BUTTON 8 The SELECT and OPTION Tags 9 The TEXTAREA Tag

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 2 of 33


name

10/24/10 6:34 PM

Reference in Musciano Book: Ch. 9 Introduction to Forms Forms are the means by which users may input information into a web page. If you've shopped or surfed on the Web at all, you've experienced forms in great variety. Have you ever typed keywords into a search field to find web pages on Google, or typed keywords into a search field to find books at Amazon.com? Those are forms! Have you purchased anything online, or requested information from a website? You certainly must have used a form to do so! If you still don't know what a form looks like, I've created a simple survey as a form example. If you clicked the Submit button in the above example, you may have noticed that clicking the Submit button did not actually accomplish anything. HTML forms are helpless without some sort of script processing them in some manner, whether CGI/PerlPHP, or JavaScript; or by using a mailto action which sends an unformatted email. There are two main types of scripts that HTML forms get processed by: CGI/Perl or PHP scripts, and JavaScript scripts. Although there is some overlap in capabilities, CGI/Perl or PHP scripts are usually used for processing form information and writing it to a database or sending it via email to someone, while JavaScript scripts are usually used for calculations (like mortgage calculations, interest calculations, etc) or browser-specific activities (like changing page locations, etc). The rule of thumb is that, if the form information needs to be in any way stored permanently in a database, communicated to a database, remembered for any length of time, or sent or communicated to the outside world, a CGI/Perl or PHP script will probably be needed; if the form information is to be used for something temporary, like a calculation or a special browser navigation function, a JavaScript script will usually be used. This distinction is breaking down as technologies advance, of course: JavaScript and Flash in combination, for instance, can be used in combination with CGI/Perl scripts and databases, and DOM specifications are being designed which will allow JavaScript scripts to one day communicate with databases directly. Still, the rule can still be generally stated that CGI scripts are required when something must be communicated to the outside world and remembered, whereas JavaScript scripts may be used when something is transient or temporary. In this module, we will be learning how to create the HTML portion of forms, and we will process the form by sending an unformatted email. I will discuss CGI and JavaScript scripts in a general way, as they relate to the HTML part of forms. I will talk about forms processing, using Perl and PHP in the next module.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 3 of 33


name

10/24/10 6:34 PM

The FORM Tag and Attributes A form is created using the FORM tag. It goes in the BODY of a regular HTML page, just like most other HTML tags. Tag: FORM Description: this tag marks the boundaries of an HTML form. This tag MUST close. There may be more than one form on an HTML page. Each FORM tag will almost always have just ONE submit button (or simulated submit button) associated with it. (Note: It is occasionally desirable to have a form submitted that will indicate certain variables, for example, different months. In this case you would use a submit button for each month; each input tag would contain the same name but a different value.) If you only see one submit button on a page, you can be sure that there's only one FORM tag present. There will NEVER be any FORM tag WITHOUT a submit button (or simulated submit button). We will talk about creating form elements and submit buttons in the next section. Example: <form> <!-- one or more form elements, with their accompanying HTML context --> <!-- a submit button --> </form>

Two attributes for the FORM tag are used when connecting a form for unformatted email or to a CGI script: METHOD and ACTION. (We will discuss CGI scripts in the next module.) Tag: FORM Attribute: METHOD Value: post or get (default) Description: this attribute defines the manner in which the form information is conveyed to a URL for providing unformatted email or conveyed to a URL containing a CGI script. Example (abbreviated): <form method="post"> <!-- all form element statements --> </form>

Tag: FORM Attribute: ACTION Value: mailto:EMAIL-ADDRESS Description: the ACTION attribute of the FORM tag connects that form to a URL for providing "insecure" email, which means that the form data is NOT encrypted, but it does NOT mean that any harm will come to your computer or to the person's computer receiving the email of the form data. It is wise not to send any sensitive data, e.g., a credit card. In this case, you must use the method of 'post', so that the email goes off without needing to be attached to anything. If using IE, when the http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 4 of 33


name

10/24/10 6:34 PM

submit button for the form is pressed, a message should pop-up, as in the following:

Clicking the 'ok' button will automatically send the email via your browser's email program; as long as you have configured the email program correctly. Note that Firefox users will not see this pop-up message. With Firefox, an email will open up with the selected name/values. Example: <form method="post" action="mailto:srubin45@comcast.net" enctype="text/plain"> <!-- all form element statements --> </form>

Note: enctype="text/plain" should be included in your form statement when sending unformatted email. It specifies the MIME type of the data to be sent by the post method. If you use Internet Explorer, the email that you receive will have as its header, "Form posted from Microsoft Internet Explorer". If you use Firefox, the email that you receive will have as its header, "Form posted from Firefox". If you do not include enctype="text/plain" in your form statement, you will be able to open the email but the data will occur in a string that will be somewhat hard to read. Regardless, the file will be called, POSTDATA.ATT. If you do include enctype="text/plain", when you open the email, you will see something that is easy to read. The above description is also true for hills email opened through pine. Note that mailto:LOGIN@hills.ccsf.edu or LOGIN@ccsf.edu, where LOGIN is your hills login, will not work. It should be LOGIN@mail.ccsf.edu To Review: The form statement should be the first statement of your form and the </form> should be the last statement of your form. For example: <form action="mailto:srubin@mail.ccsf.edu" method="post" title="Feedback Form" enctype="text/plain" name="form"> <!-- all form element statements -->

<input .... <select ... http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 5 of 33


name

10/24/10 6:34 PM

<textarea ... <input type="submit"... <input type="reset" .... </form> In Homework 8, your form statement will use a different value of the action parameter. For example: <form action="/cgi-bin/cgiwrap/srubin/form1.pl" method="post" name="myform">

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 6 of 33


name

10/24/10 6:34 PM

The INPUT Tag: Radio Buttons, Checkboxes, and Submit Buttons Form elements, such as radio buttons, checkboxes, and submit buttons, are created and inserted into a FORM using the INPUT tag. The INPUT tag doesn't require a closing tag. Tag: INPUT Description: the INPUT tag creates form elements within the confines of a FORM tag. Note: INPUT tags may ONLY be inserted as child elements of a FORM tag; they won't work outside of a FORM tag. INPUT tags require different attributes, depending on what sort of form element you're trying to create. Every INPUT tag, however, REQUIRES the TYPE attribute, which tells the browser what type of form element you want. Tag: INPUT Attribute: TYPE Value: text (default), radio, checkbox, password, submit, image, reset, button, hidden, file Description: the TYPE attribute sets the INPUT tag to become the desired type of form element. Example (abbreviated): <input type="submit" /> (makes a submit button) There are two other attributes of INPUT that are GENERALLY, though not universally, required: NAME and VALUE. Tag: INPUT Attribute: NAME Value: any name, NO SPACES IN THE NAME (and following the naming convention rules laid out in previous modules) Description: the NAME attribute of the INPUT tag identifies that INPUT for analysis in a script. Most INPUT tags require the NAME attribute. Tag: INPUT Attribute: VALUE Value: any plain text (alphanumeric) information; spaces are permissible although not always recommended. Description: the VALUE attribute of the INPUT tag allows you to assign some piece of information to a named INPUT; this information can be retrieved by a script upon submission of the form. Example (INPUT tag only): <input type="checkbox" name="pets" value="dog /">

The above example creates a checkbox named "pets" whose value is "dog". Upon submission of the form, a CGI or JavaScript script could analyze whether or not the "pets" checkbox was checked by the user; if the "pets" checkbox was checked, the script could extract the value "dog" from that checkbox.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 7 of 33


name

10/24/10 6:34 PM

Checkboxes Let's take a closer look at the "pets" checkbox from the previous example. Here is a complete HTML page, including a FORM tag, which uses the "pets" checkbox code: <html> <head> <title>Example Form</title> </head> <body> <form> <input type="checkbox" name="pets" value="dog" /> </form> </body> </html>

Here it is displayed.

Notice how there is NOTHING visible but the checkbox? You can't see the name "pets" or the value "dog"; these things are invisible to the user. The INPUT tag creates ONLY the form element itself; it does not create any context for the form element. Context for a form element must be created using ordinary HTML code and text. Here is an example of the plainest possible HTML formatting for a set of checkboxes: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose one or more of your favorite pets:<br> <input type="checkbox" name="pets" value="dog" /> Dog<br> <input type="checkbox" name="pets" value="cat" /> Cat<br> <input type="checkbox" name="pets" value="bird" /> Bird</p> </form> </body> </html>

Here it is displayed. Choose one or more of your favorite pets: Dog Cat Bird The use of the P tag to mark the entire set of inputs, including their opening line, is very standard. Notice how all of the checkboxes in this group have the same NAME, while the VALUEs are all http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 8 of 33


name

10/24/10 6:34 PM

different? You will usually name all checkboxes in a single group the same thing, or they will not operate properly when being analyzed by most scripts. An exception to this rule is when using a php script with checkboxes. There must be NOTHING else on the HTML page which uses that NAME, however; each named element on an HTML page must have a UNIQUE name (a named element being anything using the NAME attribute, regardless of the tag).

Submit Buttons As mentioned earlier, a form isn't a form without a submit button to allow the user to submit the form for processing by a script. The submit button is created using the INPUT tag, type="submit". Example (INPUT only): <input type="submit" value="Submit Me, Please" />

The VALUE of a submit button is the text which appears on the button itself. Here is the above submit button in context with the set of checkboxes from the previous example: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose one or more of your favorite pets:<br> <input type="checkbox" name="pets" value="dog" /> Dog<br> <input type="checkbox" name="pets" value="cat" /> Cat<br> <input type="checkbox" name="pets" value="bird" /> Bird</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here it is displayed. Choose one or more of your favorite pets: Dog Cat Bird Submit Me, Please

Again, notice how the submit INPUT tag's VALUE is the text appearing in the button itself?

Radio Buttons Radio buttons are coded identically to checkboxes, with one exception: the TYPE attribute must be http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 9 of 33


name

10/24/10 6:34 PM

set equal to "radio". Example: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose your favorite type of <input type="radio" name="pets" <input type="radio" name="pets" <input type="radio" name="pets"

pet:<br> value="dog" />Dog<br /> value="cat" />Cat<br /> value="bird" />Bird /</p>

<input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here it is displayed. Choose your favorite type of pet: Dog Cat Bird Submit Me, Please

Radio buttons behave differently from checkboxes in one important respect: the user may check only ONE from a group of radio buttons, whereas they may check as many as they like from a group of checkboxes. That is the essential nature of radio buttons. It is important that all radio buttons in a group have the same NAME, or they will absolutely NOT function properly for the user. In the following example, I have NAMED each of my radio buttons something different; witness the sad result for yourself. Choose your favorite type of pet: Dog Cat Bird Submit Me, Please

Once you've checked all the buttons once, you can't UNCHECK them, nor can you get them to behave like proper radio buttons. Here is another example which you may find illuminating. I have created two sets of radio buttons, http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 10 of 33


name

10/24/10 6:34 PM

one named "pets" and one named "colors". In the "colors" set of radio buttons, I have "accidentally" named one of the inputs "pets" by mistake. Here is the code: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose your favorite type of <input type="radio" name="pets" <input type="radio" name="pets" <input type="radio" name="pets"

pet:<br> value="dog" /> Dog<br> value="cat" /> Cat<br> value="bird" /> Bird</p>

<p>Choose your favorite color:<br> <input type="radio" name="colors" value="red" /> Red<br> <input type="radio" name="colors" value="green" /> Green<br> <input type="radio" name="pets" value="blue" /> Blue</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

And here is the above example displayed. Choose your favorite type of pet: Dog Cat Bird Choose your favorite color: Red Green Blue Submit Me, Please

If you click on the "pets" radio buttons, everything seems fine. But if you click on the "blue" radio button in the "colors" group (which was named "pets" by mistake), it operates in tandem with the "pets" radio buttons rather than the "colors" radio buttons, causing the "pets" buttons to lose their checked choice. It doesn't matter how far apart these INPUT tags are in the FORM, or where they're located or what they're grouped with; if they have the same NAME attribute, they are going to operate together as a group, regardless of their context. Since you don't want this sort of bizarre behavior to occur, you need to be very careful when coding your radio buttons and checkboxes, making CERTAIN that all of the NAMEs in a given group are indeed identical, and that no other group contains a repeat of that http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 11 of 33


name

10/24/10 6:34 PM

NAME. Here is the corrected example: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose your favorite type of <input type="radio" name="pets" <input type="radio" name="pets" <input type="radio" name="pets"

pet:<br> value="dog" /> Dog<br> value="cat" /> Cat<br> value="bird" /> Bird</p>

<p>Choose your favorite color:<br> <input type="radio" name="colors" value="red" /> Red<br> <input type="radio" name="colors" value="green" /> Green<br > <input type="radio" name="colors" value="blue" /> Blue</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

And here is that corrected example displayed. Choose your favorite type of pet: Dog Cat Bird Choose your favorite color: Red Green Blue Submit Me, Please

Students always ask me, "Can I make radio buttons behave like checkboxes, or checkboxes behave like radio buttons?" The answer is NO, you can not; radio buttons behave and look like radio buttons and may not be anything else, and the same holds true for checkboxes. These form elements and their behaviors are built into the browsers as common RESOURCES for web programmers, so that there are consistent-looking-and-acting interface elements available to users, and they may not be altered arbitrarily. The second question students ask me is "Can I change the appearance of these form elements, or use my own images in place of the boring buttons?" The answer to that question is NO, not significantly. Some form elements may be altered in appearance SLIGHTLY using CSS, but not in any substantive http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 12 of 33


name

10/24/10 6:34 PM

way, and it is physically impossible to substitute custom graphics for any form element except for the submit button (which we'll talk about later).

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 13 of 33


name

10/24/10 6:34 PM

The METHOD Attribute of the FORM Tag Now that you know about creating checkboxes, radio buttons, and submit buttons within a FORM tag, we need to look once more at the METHOD attribute of the FORM tag. Here is the code from the example from the previous section: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose your favorite type of <input type="radio" name="pets" <input type="radio" name="pets" <input type="radio" name="pets"

pet:<br> value="dog" /> Dog<br> value="cat" /> Cat<br> value="bird" /> Bird</p>

<p>Choose your favorite color:<br> <input type="radio" name="colors" value="red" /> Red<br> <input type="radio" name="colors" value="green" /> Green<br> <input type="radio" name="colors" value="blue" /> Blue</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

And here is the example displayed. Make a choice from each group of radio buttons in this example and click the submit button as shown in the following illustration:

Look in the location bar of the browser (where the URL for the current page is displayed), as shown in the following illustration:

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 14 of 33


name

10/24/10 6:34 PM

You will notice that a question mark (?) has been added to the end of the URL for the current page, and see so-called "name-value pairs" appended onto the end of the URL following the question mark (in the example above, the name-value pairs are "pets=cat" and "colors=red"). When a FORM is submitted, the various form elements in the FORM may be converted into namevalue pairs derived from the values of their NAME and VALUE attributes, e.g. NAME=VALUE. When there is more than one name-value pair in a FORM, the ampersand (&) character is inserted between the pairs. These name-value pairs may be looked at by a script analyzing a FORM. The text comprised of the question mark followed by name-value pairs in the web browser's location bar is called a "query string". When a FORM has its METHOD attribute set equal to "get" (the default value), clicking on the submit button causes the browser to extract all of the chosen name-value pairs from the FORM; these name-value pairs are then converted into a query string which is appended onto the end of the URL in the web browser's location bar. When a FORM has its METHOD attribute set equal to "post", the form information is submitted in a manner which does not need further explanation at this time. With method="post", the submission process is invisible to the user. If you are utilizing a form action of 'mailto', then you should use method="post". When creating HTML forms, you should use method="post" whenever there is form information which needs to remain "secret" (e.g. not displayed in the location bar), such as password information, etc; but some of the time, you may wish to use method="get" (which is the same as not setting the METHOD attribute at all).

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 15 of 33


name

10/24/10 6:34 PM

The INPUT Tag: TEXT and PASSWORD Text INPUT Field Creating a single line text input field is simplicity itself. You'll need the INPUT tag with its TYPE attribute set equal to "text", the NAME attribute, and the SIZE attribute; the VALUE attribute is not necessary with a text INPUT field. Tag: INPUT Attribute: SIZE Value: an integer representing the number of characters wide the TEXT INPUT field will be (using the browser's default monospace font, usually Courier or Courier New 10 point). Description: The SIZE attribute of the INPUT tag determines the width of a text input field. Example (abbreviated): <input type="text" size="30" name="fred" />

Here is an example using the text INPUT in context: <html> <head> <title>Example Form</title> </head> <body> <form> <p>First Name:<br> <input type="text" size="30" name="firstName" /></p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed: First Name:

Submit Me, Please

If you submit this form, you will notice that the name-value pair in the query string is "firstName=somename" (where "somename" is whatever you have typed). The VALUE of a text INPUT field is whatever the user types into the text field; this is why you don't need to set a VALUE attribute for a text INPUT field. In the following example, I have "mistakenly" set a VALUE attribute for the text INPUT field: <p>First Name:<br> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 16 of 33


name

10/24/10 6:34 PM

<input type="text" size="20" name="firstName" value="Steve" /></p>

Let us look at this example: First Name: Steve Submit Me, Please

The first thing you will notice is that the text INPUT field says "Steve" in it, which is the value of the VALUE attribute; this default text is not considered to be desirable. Users expect text INPUT fields to be blank when they encounter one; you must therefore NOT set the VALUE attribute of the INPUT tag when creating text INPUT fields. You may also notice that you can type more content into one of these text INPUT fields. In some cases, however, you may wish to restrict the number of characters typed into the text INPUT field; to do this, you must set the MAXLENGTH attribute. Tag: INPUT Attribute: MAXLENGTH Value: an integer representing the maximum number of characters the user may type into this particular text INPUT field. Description: the MAXLENGTH attribute restricts the number of characters a user may type into a text INPUT field. Example: <html> <head> <title>Example Form</title> </head> <body> <form> <p>First Name:<br> <input type="text" size="20" maxlength="30" name="firstName" /></p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

And here is the above example displayed. First Name:

Submit Me, Please

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 17 of 33


name

10/24/10 6:34 PM

By setting the MAXLENGTH attribute equal to "30", we have restricted the number of characters the user may type into the field to 30 characters (that includes spaces, punctuation, etc). The MAXLENGTH attribute may be set to any number, regardless of the SIZE of the field; for instance, MAXLENGTH might be less than or greater than the SIZE attribute value. You would probably only need to restrict a text INPUT field using MAXLENGTH if you know you are going to be using the information gained for a particular purpose, such as printing names and addresses onto physical mailing labels (which have a maximum number of characters they can accept before running out of space). Generally, however, you don't need to set MAXLENGTH.

Password INPUT Field Password INPUT fields are identical to text input fields (including the way they use SIZE and MAXLENGTH attributes) except for their use of the "password" value for the TYPE attribute. Example: <html> <head> <title>Example Form</title> </head> <body> <form> <p>Login Name:<br> <input type="password" size="30" maxlength="30" name="thePassword" /></p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed. There is only one problem with the above example: if you submit the form, you can see the supposedly "secret" password displayed in the location bar of the browser; since you're not EVER supposed to be able to see a password (that's why the letters are blocked out in the field itself), users think that there's been some sort of security breach when the password appears as part of a query string. Whenever you use a password INPUT field in a form, you MUST set the METHOD attribute of the FORM tag equal to "post"; this will hide the password from the user at all times. Example: <html> <head> <title>Example Form</title> </head> <body> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 18 of 33


name

10/24/10 6:34 PM

<form method="post"> <p>Login Name:<br> <input type="password" size="30" maxlength="30" name="thePassword" /></p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Remember, the password INPUT field doesn't actually have any real security attached to it beyond obscuring the letters with bullets. Real security requires a secure server connection using the "https" scheme and an appropriate server. HTML forms themselves have NO security built into them.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 19 of 33


name

10/24/10 6:34 PM

The INPUT Tag: the CHECKED Attribute and the Reset Button Radio buttons and checkboxes may be pre-checked by using the CHECKED attribute of the INPUT tag. Tag: INPUT Attribute: CHECKED Value: CHECKED Description: cause radio buttons and checkboxes to be pre-checked by setting the CHECKED attribute of the INPUT tag. Note that XHTML requires a value of "checked", whereas HTML requires no value. Example (abbreviated): <input type="checkbox" name="pets" value="cat" checked="checked" />

Example: <input type="checkbox" name="pets" value="cat" checked="checked" />

Example (in context): <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose one or more of your favorite pets:<br> <input type="checkbox" name="pets" value="dog" checked="checked" /> Dog<br> <input type="checkbox" name="pets" value="cat" checked="checked" /> Cat/<br> <input type="checkbox" name="pets" value="bird" /> Bird</p> <p>Choose your favorite color:<br> <input type="radio" name="colors" value="red" checked="checked" /> Red<br> <input type="radio" name="colors" value="green" /> Green<br> <input type="radio" name="colors" value="blue" /> Blue</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed. Choose one or more of your favorite pets: Dog Cat http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 20 of 33


name

10/24/10 6:34 PM

Bird Choose your favorite color: Red Green Blue Submit Me, Please

Remember: only ONE radio button may be pre-checked, while as many checkboxes as you like may be pre-checked. Pre-checked checkboxes are common on websites which are soliciting your personal information for mailing lists, as in this brief example; I don't recommend doing this, however, as it annoys users and adds unhappy people to your database. Make certain to allow users to check their OWN "add me to the mailing list" box, so that they will only receive your mailings if they REALLY want them; this makes for happier users who are more truly interested in hearing about your offerings.

The Reset INPUT Most forms use some sort of "reset" or "clear" button to allow users to reset a form to its default state. The reset INPUT is created by setting the TYPE attribute of the INPUT tag equal to "reset"; you would also set the VALUE attribute of the INPUT tag equal to whatever text you wanted to have appear inside the reset button. Example (abbreviated): <input type="reset" value="Clear Me, Please" />

Example (in context): <html> <head> <title>Example Form</title> </head> <body> <form> <p>Choose one or more of your favorite pets:<br> <input type="checkbox" name="pets" value="dog" checked="checked" /> Dog<br> <input type="checkbox" name="pets" value="cat" checked="checked" /> Cat<br> <input type="checkbox" name="pets" value="bird" /> Bird</p> <p>Choose your favorite color:<br> <input type="radio" name="colors" value="red" checked="checked" /> Red<br> <input type="radio" name="colors" value="green" /> Green<br> <input type="radio" name="colors" value="blue" /> Blue</p> <input type="submit" value="Submit Me, Please" /> <input type="reset" value="Clear Me, Please" />

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 21 of 33


name

10/24/10 6:34 PM

</form> </body> </html>

Here is the above example displayed. The reset button does NOT completely empty a form; it merely resets a form to its initial state, whatever that is. You will notice that, even though this button is technically a RESET button, most web programmers call it a "clear" button, and use "Clear This Form" or "Clear" as the VALUE for the reset INPUT tag; this does not affect its functionality. Most forms include both a submit button and a reset button.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 22 of 33


name

10/24/10 6:34 PM

The INPUT Tag: IMAGE and BUTTON Having dealt with the most important members of the INPUT tag family, we now turn to two lesser, but no less useful, variations, IMAGE and BUTTON. The IMAGE INPUT allows us to substitute a GIF or JPEG for a regular submit button, while the BUTTON INPUT allows us to create a submitlike button that does nothing at all. The uses for the IMAGE INPUT seem obvious, but the uses for the BUTTON INPUT are only open to those who use JavaScript scripts to add functionality to plain HTML elements.

Image INPUT The image INPUT requires that the TYPE attribute for the INPUT tag be set equal to "image". In addition to the TYPE attribute, you also need to use the SRC, WIDTH, and HEIGHT attributes of the IMG tag. Example (abbreviated): <input type="image" src="mod8ggo.gif" width="50" height="50" />

Example (in context): <html> <head> <title>Example Form</title> </head> <body> <form> <p>Search Keywords:<br> <input type="text" size="40" name="searchKeywords" /></p> <input type="image" src="mod8ggo.gif" width="50" height="50" /> </form> </body> </html>

Here is the above example displayed. As you may be able to see in the example, the new image INPUT has a hot-link border around it (in most browsers), which is not usual on the Web today. To prevent the appearance of the border, you must set the BORDER attribute of the INPUT tag equal to "0" (zero). Example (abbreviated): <input type="image" src="mod8ggo.gif" width="50" height="50" border="0" />

Example (in context): <html> <head> <title>Example Form</title> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 23 of 33


name

10/24/10 6:34 PM

</head> <body> <form> <p>Search Keywords:<br> <input type="text" size="40" name="searchKeywords" /></p> <input type="image" src="mod8ggo.gif" width="50" height="50" border="0" /> </form> </body> </html>

Being able to substitute a graphic of your own design for the submit button is very helpful to the designer. The image INPUT may NOT be used as a substitute for anything other than the submit button, however.

Button INPUT The button INPUT is coded identically to the submit and reset buttons; the only difference is that the button INPUT has no specific function, but acts as a generic button for use in conjunction with a script. Example: <form> <input type="button" value="Do-Nothing Button" /> </form>

Displayed: Do-Nothing Button

In addition to the button INPUT, there are two final variations of the INPUT tag, FILE and HIDDEN. The file INPUT allows the programmer to create a text field which may be used to find and submit files to a server. The hidden INPUT is invisible to the user entirely and has many uses. We will see a good use of the INPUT tag and HIDDEN for PHP in assignment 8.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 24 of 33


name

10/24/10 6:34 PM

The SELECT and OPTION Tags The SELECT and OPTION tags are used to create pulldown menus and multiple-choice scrollboxes for forms, as in this example. As with the INPUT tag, the SELECT and OPTION tags must only be used as child elements of the FORM tag.

Pulldown Menus To create a pulldown menu, one must first lay a SELECT tag within a FORM. Example: <form> <select> </select> </form>

The SELECT tag has one important attribute, NAME, which is just like the NAME attribute of the INPUT tag. Example: <form> <select name="colors"> </select> </form>

Once you've laid in the SELECT tag, you must create one OPTION tag for every desired option in the pulldown menu. The text that you want to see in the pulldown menu itself is placed between the opening and closing OPTION tags. Example (one option): <form> <select name="colors"> <option>Red</option> </select> </form>

The OPTION tag has one attribute, VALUE, which is just like the VALUE attribute of the INPUT tag. If the value attribute is NOT specified, the value of the option is set to the content of the <option> tag Example WITH value attribute (multiple options): <form> <select name="colors"> <option value="red">Red</option> <option value="green">Green</option> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 25 of 33


name

10/24/10 6:34 PM

<option value="blue">Blue</option> </select> </form>

Example WITHOUT value attribute (multiple options): <form> <select name="colors"> <option>Red</option> <option>Green</option> <option>Blue</option> </select> </form>

Both examples displayed: Red

Example (with context): <form> <p>Choose your favorite color: <select name="colors"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select></p> </form>

Displayed: Choose your favorite color:

Red

As you can see above, the SELECT tag gets the NAME attribute, while each separate OPTION tag gets its own VALUE attribute; in this way, they are much like a group of radio buttons in a different format. You may see just how the name-value pairs for the pulldown menu resolve when you click on the submit button in the following example: <html> <head> <title>Example Pulldown Menu Form</title> </head> <body> <form method="get"> <p>Choose your favorite color: <select name="colors"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select></p> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 26 of 33


name

10/24/10 6:34 PM

<input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed. As you may have noticed, the FIRST option in the pulldown menu appears as the default choice in the pulldown menu when the HTML page is loaded. You may pre-select any one of the other options in the pulldown menu by adding the SELECTED attribute to the appropriate OPTION tag. Tag: OPTION Attribute: SELECTED Value: SELECTED Description: whichever OPTION tag contains the SELECTED attribute becomes the default choice in the pulldown menu. Note that XHTML requires a value of "selected", whereas HTML requires no value. Example (abbreviated): <option value="blue" selected="selected">

Example (in context): <html> <head> <title>Example Pulldown Menu Form</title> </head> <body> <form method="get"> <p>Choose your favorite color: <select name="colors"> <option value="red">Red</option> <option value="green">Green</option> <option value="blue" selected="selected">Blue</option> </select></p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed. The VALUE attribute of the OPTION tag does NOT have to be the same value as the text appearing in the pulldown menu itself. This is a particularly useful feature when creating pulldown menus which will be used for navigation on a website. Example: <html> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 27 of 33


name

10/24/10 6:34 PM

<head> <title>Example Pulldown Menu Form</title> </head> <body> <form method="get"> <p>Choose your favorite website: <select name="website"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.shockwave.com/">Shockwave</option> <option value="http://fog.ccsf.org/~srubin/" selected="selected">Steve Rubin</option> </select></p> <input type="submit" value="Go"> </form> </body> </html>

Here is the above example displayed. Notice how this form is HELPLESS without a script to power it? It doesn't matter that I've placed URLs in VALUE attributes of the OPTION tags; I need to process those URLs using some sort of script, before this form will be able to execute any sort of real action.

Multiple Choice Scrollboxes Multiple choice scrollboxes are coded identically to pulldown menus, with the addition of two attributes to the SELECT tag: SIZE and MULTIPLE. The SIZE attribute converts the SELECT tag into a scrollbox, while the MULTIPLE attribute allows the user to choose more than one item at a time. Tag: SELECT Attribute: SIZE Value: an integer representing the number of lines tall the scrollbox will be; this integer should always be at least "4" (it may be greater) to insure that the complete scrollbox will be accessible on both Mac and PC platforms (Note: if SIZE is set too small, some users may not be able to operate the scrollbar properly). Description: the SIZE attribute of the SELECT tag creates a scrollbox of options rather than a pulldown menu. Example (abbreviated): <select name="fred" size="4">

Tag: SELECT Attribute: MULTIPLE Value: none Description: allows a scrollbox to record multiple choices by the user; this functionality requires that the user hold down the "Command" key (Mac) or the "Control" key (PC) while clicking in order to make non-contiguous multiple choices. Holding down the "shift" key while clicking allows the user to choose a contiguous range of multiple choices. http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 28 of 33


name

10/24/10 6:34 PM

Example (abbreviated): <select name="fred" size="4" multiple>

Example (in context): <html> <head> <title>Multiple Choice Scrollbox</title> </head> <body> <form method="get"> <p>Choose one or more of your favorite colors:<br> <select name="colors" size="4" multiple> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> <option value="orange">Orange</option> <option value="violet">Violet</option> <option value="aqua">Aqua</option> <option value="yellow">Yellow</option> </select></p> <p>Scrollbox Use Instructions: hold down the "shift" key while clicking to make multiple contiguous choices; hold down the "command" key (Mac) or the "control" key (PC) while clicking to make multiple non-contiguous choices.</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed Because multiple choice scrollboxes are not in common use, users do not know exactly how to operate them. Therefore, instructions for making multiple selections MUST be included in any form which uses multiple choice scrollboxes. Just as with the regular pulldown menu, the SELECTED attribute may be added to any OPTION tag which you wish to make pre-selected; unlike the pulldown menu, more than one OPTION tag may be pre-selected. Example (in context): <html> <head> <title>Multiple Choice Scrollbox</title> </head> <body> <form method="get"> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 29 of 33


name

10/24/10 6:34 PM

<p>Choose one or more of your favorite colors:<br> <select name="colors" size="4" multiple"> <option value="red" selected="selected">Red</option> <option value="green">Green</option> <option value="blue" selected>Blue</option> <option value="orange">Orange</option> <option value="violet" selected="selected">Violet</option> <option value="aqua">Aqua</option> <option value="yellow">Yellow</option> </select></p> <p>Scrollbox Use Instructions: hold down the "shift" key while clicking to make multiple contiguous choices; hold down the "command" key (Mac) or the "control" key (PC) while clicking to make multiple non-contiguous choices.</p> <input type="submit" value="Submit Me, Please" /> </form> </body> </html>

Here is the above example displayed Personally, I stay away from multiple choice scrollboxes in favor of regular checkboxes (which are easier for users to understand and operate). However, there are times when multiple choice scrollboxes are really the best form element for a job; don't forget to include instructions.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 30 of 33


name

10/24/10 6:34 PM

The TEXTAREA Tag The TEXTAREA tag creates a multiple-line text input field within a FORM; here is an example.

Tell me your life story:

Submit This Puppy

TEXTAREA requires three attributes: NAME, COLS, and ROWS. NAME names the TEXTAREA so that it can be accessed by the script, COLS determines the width of the TEXTAREA, and ROWS determines the height of the TEXTAREA. The TEXTAREA tag always closes. Tag: TEXTAREA Attribute: NAME Value: any valid name (following the naming conventions outlined in previous modules) Description: the NAME attribute of the TEXTAREA tag identifies the TEXTAREA so that it may be accessed by a script. Tag: TEXTAREA Attribute: COLS Value: an integer representing the number of characters wide the TEXTAREA will be. As with the text INPUT, these characters are in the web browser's default monospace font (usually Courier or Courier New 10 point). Description: the COLS attribute of the TEXTAREA tag sets the width of the TEXTAREA. Tag: TEXTAREA Attribute: ROWS Value: an integer representing the number of lines of text tall the TEXTAREA will be. Description: the ROWS attribute of the TEXTAREA tag sets the height of the TEXTAREA. Example (abbreviated): <textarea name="theMessage" cols="40" rows="4"></textarea>

Example (in context): <html> <head> <title>TEXTAREA Tag</title> </head> <body> http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 31 of 33


name

10/24/10 6:34 PM

<form> <p>Tell me your life story:<br> <textarea name="lifeStory" cols="40" rows="5"></textarea></p> <input type="submit" value="Submit This Puppy" /> </form> </body> </html>

Again, here is the above example displayed.

Tell me your life story:

Submit This Puppy

You will note that there is no VALUE attribute assigned to TEXTAREA. The VALUE of a TEXTAREA is whatever text is placed between the opening and closing TEXTAREA tags. Example (abbreviated): <textarea name="lifeStory" cols="40" rows="5">Type your life story here...</textarea>

Example (in context): <html> <head> <title>TEXTAREA Tag</title> </head> <body> <form> <p>Tell me your life story:<br> <textarea name="lifeStory" cols="40" rows="5">Type your life story here...</textarea></p> <input type="submit" value="Submit This Puppy" /> </form> </body> </html>

Here is the above example displayed.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 32 of 33


name

10/24/10 6:34 PM

Tell me your life story: Type your life story here...

Submit This Puppy

When the TEXTAREA tag was first created, it was felt that users might not understand that they needed to type into the TEXTAREA. It was common practice, therefore, to place some text between the opening and closing TEXTAREA tags to indicate where the user was to type; the user could replace this text with their own text, which would automatically become the new VALUE for the TEXTAREA. This functionality was soon discovered to be unnecessary; users automatically understood that they could type into the TEXTAREA. Today, no one pre-sets a value for the TEXTAREA in this manner. Again, leave the TEXTAREA as an empty tag; always remember to close it, as shown in the first example.

http://insight.ccsf.edu/mod/book/print.php?id=136104

Page 33 of 33


name

11/3/10 9:47 AM

Book 8: CGI Scripts Book for Weeks 13-15:

CGI Scripts

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 8: CGI Scripts Printed by: Donald Siino Date: Wednesday, 3 November 2010, 09:47 AM

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 1 of 20


name

11/3/10 9:47 AM

Table of Contents 1 Forms and Introduction to CGI 2 Introduction to Perl 3 A Simple Example using Perl 4 Debugging Perl Errors 5 Introduction to PHP

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 2 of 20


name

11/3/10 9:47 AM

Forms and Introduction to CGI Because forms are usually so bound up with scripting languages, some discussion of scripts and scripting languages, and how scripts relate to forms, is necessary. This discussion will entail some jumping around between regular HTML and more esoteric CGI scripting information. As discussed in the previous module, a form is created using the FORM tag. It goes in the BODY of a regular HTML page, just like most other HTML tags. Example: <form> <!-- one or more form elements, with their accompanying HTML context --> <!-- a submit button --> </form>

Now we need to talk about CGI scripts. CGI stands for Common Gateway Interface. All web servers have CGI capabilities. The CGI is the means for web pages to communicate with the server directly, with power to read and rewrite information on the server hard drive, whether in a database or in a more ordinary directory or file. CGI scripts can be written in any programming language, including C, C++, Java, Perl and PHP. Perl and PHP are the two most common programming languages used for writing CGI scripts as regards web pages and forms. Because CGI scripts have the power to rewrite or erase a web server's hard drive, they are considered to be a potential security hazard or security breach by web server administrators (with good reason!). Unless you have special privileges or direct physical access to an actual web server computer, you will probably not be allowed to write CGI scripts yourself. Web servers have something called the "cgi-bin", which is simply a directory on the server which contains all of the CGI scripts for that server. These CGI scripts may be accessed if you know the URL for the script and its "cgi-bin" directory. Most ISPs (Internet Server Providers) have a collection of CGI scripts available to their customers, and have published FAQ sheets on their website which give information on how to connect your HTML pages and HTML forms to these pre-made CGI scripts. Have you ever seen a "counter" on a web page which tells you how many people have visited that page? That counter is created using a commonly-available CGI script. There is also a very common CGI script which takes the contents of an HTML form, converts that information into text, inserts the text into the body of an email message, and sends that email to whomever has been specified. These scripts, and many more, are usually readily available in the cgi-bin of any ISP. If you register your own domain name in combination with an ISP, your ISP server administrator may be able to give you a separate cgi-bin for your domain. If you arrange for a separate cgi-bin for http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 3 of 20


name

11/3/10 9:47 AM

your domain, you will no longer have access to the main cgi-bin for the ISP (with its accompanying scripts), but you WILL be able to write your own CGI scripts, if that is important to you. Again, if you work for a company with its own web server and you have access privileges to the actual web server computer, you will probably be able to write CGI scripts and drop them directly into the cgibin on that computer. CGI scripts usually come with one of two dot-extensions on the file name, ".cgi" (for a generic CGI script) and ".pl" (for a Perl script specifically). A good introduction to CGI can be found at http://hoohoo.ncsa.uiuc.edu/cgi/intro.html. "The Common Gateway Interface (CGI) is a standard for interfacing external applications with information servers, such as HTTP or Web servers. A plain HTML document that the Web daemon retrieves is static, which means it exists in a constant state: a text file that doesn't change. A CGI program, on the other hand, is executed in real-time, so that it can output dynamic information. For example, let's say that you wanted to "hook up" your Unix database to the World Wide Web, to allow people from all over the world to query it. Basically, you need to create a CGI program that the Web daemon will execute to transmit information to the database engine, and receive the results back again and display them to the client. This is an example of a gateway, and this is where CGI got its origins. The database example is a simple idea, but most of the time rather difficult to implement. There really is no limit as to what you can hook up to the Web. The only thing you need to remember is that whatever your CGI program does, it should not take too long to process. Otherwise, the user will just be staring at their browser waiting for something to happen." Now, back to the FORM tag. The FORM tag has a few attributes which relate to connecting it to a script. You will need to understand what they are, what they do, and what type of scripts they relate to. Two attributes for the FORM tag are used when connecting a form to a CGI script: METHOD and ACTION. Tag: FORM Attribute: METHOD Value: get (default) or post Description: this attribute defines the manner in which the form information is conveyed to the script. Example (abbreviated): <form method="post"> <!-- one or more form elements, with their accompanying HTML context --> <!-- a submit button -->

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 4 of 20


name

11/3/10 9:47 AM

</form>

Tag: FORM Attribute: ACTION Value: a URL (to the CGI script in the cgi-bin in question) Description: the ACTION attribute of the FORM tag connects that form to a CGI script; when the submit button for the form is pressed, the web browser seeks out the CGI script at the URL indicated by the value of ACTION and causes the web server to execute that CGI script. Example (abbreviated): <form method="post" action="/cgi-bin/myScript.cgi"> <!-- one or more form elements, with their accompanying HTML context --> <!-- a submit button --> </form> Example (abbreviated): <form method="post" action="/cgi-bin/cgiwrap/srubin/form1.pl"> <!-- one or more form elements, with their accompanying HTML context --> <!-- a submit button --> </form>

Again, both the METHOD and the ACTION attributes are required when connecting a form to a CGI script.

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 5 of 20


name

11/3/10 9:47 AM

Introduction to Perl Perl is an abbreviation for Practical Extraction and Report Language. It's original purpose was to monitor large software projects and generate reports. It was initially developed on Unix. Perl is one of two languages that are most commonly used in a cgi script to process forms on the Web. This is because most of the information that users send to servers is text, such as usernames, passwords, and email addresses. Perl is the language that you will use to process your form in Homework 8a. I will be explaining to you only the necessary Perl statements to complete this homework assignment. The explanation of each relevant Perl statement can be found in the comment statements (those that begin with #) of the sample Perl script that is illustrated on the next page, and in the sample Perl script associated with the sample web page for Homework 8a. Mainly, what you will do is to copy my Perl sample script, and then modify it to accommodate your own specifications in processing your form in Homework 8a. When you copy my script, be sure to save it as form1.pl.The modifications on your perl script involve: 1. changing the variables within each occurrence of $in to match your variable names in your form. 2. changing the information in the HTML portion to reflect the web page that your perl script will return to the browser. You may wish to read the tutorials on Perl at the following URLs: http://pageresource.com/cgirec/index2.htm http://www.perlaccess.com/tutorials/General/ http://www.htmlgoodies.com/primers/perl/

Basics of using a Perl script on the hills server To get a Perl script to work with a form, you'll need to do the following: Create a subdirectory of your public_html directory, called cgi-bin Put the script file in cgi-bin Give unix execute permission for the script file and the cgi-bin subdirectory Refer to it in the ACTION attribute of your Homework 9a web page as: ACTION="/cgi-bin/cgiwrap/jstudent/form1.pl" where jstudent is your login ID, and form1.pl is the actual name of the script file

Elements of Perl http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 6 of 20


name

11/3/10 9:47 AM

Semi-colons and case-sensitivity. All statements in Perl must end in a semi-colon. This lets Perl know when to stop one idea and start the next one. Perl is case-sensitive - upper and lower case letters are treated differently. The First Line. The first line of all your Perl scripts should be: #!/usr/local/bin/perl This tells hills to execute the program that follows using Perl. If you are ever creating Perl scripts that will run on a different Unix machine (other than hills), you may need to change this first line, since it is machine dependent. Comments. Any line, except for the first line, that starts with a pound sign (#) is a comment. Comments are used to make your Perl scripts easier to understand. Variables. Variables in a Perl script start with a $. For example, $in{'choice'}, would refer to the contents of the value attribute that is associated with name="choice" in your HTML form page. Print Statements. Print statements are used to output information to an output device such as a screen. Example 1: print "<h2>Rubin's Form</h2>"; This statement would output the header, Rubin's Form. Example 2: print<<"_END_"; This line says to output the following information, until the statement _END_; is reached To get a more complete understanding of Perl, you should take CS 113A

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 7 of 20


name

11/3/10 9:47 AM

Example of a simple form and the perl script that processes it. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>forms page</title> </head> <body> <form method="post" action="/cgi-bin/cgiwrap/srubin/test.pl"> <h3>A Simple Form</h3> <p>Which course was your favorite?</p> <p> <select name="fav"> <option>CNIT 131</option> <option selected="selected">CNIT 132</option> <option>CNIT 133</option> </select> </p> <p>Which course was your least favorite?</p> <p><input type="radio" name="least" value="cnit131" checked="checked" />CNIT 131 <input type="radio" name="least" value="cnit132" />CNIT 132 <input type="radio" name="least" value="cnit133" />CNIT 133</p> <p>Comments/Questions<br /> <textarea name="comments" rows="4" cols="40"></textarea></p> <p><input type="submit"> <input type="reset" /></p> </form> </body>

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 8 of 20


name

11/3/10 9:47 AM

</html>

Here is the perl script, named test.pl, that actually processes the submitted information from the form and returns the processed information as a web page. #!/usr/local/bin/perl do "cgi-lib.pl" ||die "Fatal Error: Can't load cgi library"; #calls subroutine in cgi-lib.pl library &ReadParse; # The above line reads the stream of name=value pairs from the form # and puts the values in a perl table called in print "Content-type: text/html\n\n"; # in perl a \n is a "carriage return, next line" # NOTE: the text/html indicates the MIME type of # information that the # script is sending back to the browser thru the Web server # The items within the braces below refer to the name contents found within the form. # The next line says to output the following information, until # the statement _END_; is reached print<<"_END_"; <html> <head> <title>Form Page</title> </head> <body> <p>You indicated that your favorite class is $in{'fav'}</p> <p>You indicated that your least favorite class is $in{'least'}</p> <p>The value of comments is $in{'comments'}</p> </body> http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 9 of 20


name

11/3/10 9:47 AM

</html> _END_ ;

Here is the above form displayed and it's corresponding perl script.

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 10 of 20


name

11/3/10 9:47 AM

Debugging Perl Errors Typical Errors when processing a form with a Perl script 1. 2. 3. 4. 5.

cgi-bin is not a subdirectory of public_html Your Perl script is not in your cgi-bin subdirectory Your Perl script was uploaded to cgi-bin in binary mode cgi-bin and/or your perl script do not have unix execute permission Your FORM action statement in your FORM HTML page is incorrect For Example: <form action="/cgi-bin/cgi-wrap/srubin/form1.pl" method="Post"> (Note the misspelling of cgiwrap) 6. Your Perl script has errors. This is the most common error. Some typical Perl errors are: misspelled keyword, e.g., primt instead of print missing semi-colon, e.g., &ReadParse instead &ReadParse; an intended comment that does NOT start with # a variable name in $in{...} that doesn't match the corresponding variable name in your form. This is a very common error. having a blank line as the first line. Here is a correct form and the corresponding correct Perl script.

Typical Error Scenarios Example 1: Reason for error: failure to give unix execute permission to your Perl script Here is the example displayed. Click on the submit button of the form to see the error message.

Debugging Fix: give unix execute permission to your Perl script Example 2: Reason for error: your Perl script is not in cgi-bin Here is the example displayed. Click on the submit button of the form to see the error message.

Debugging Fix: put Perl script in cgi-bin Example 3: Reason for error: in your Form HTML file, the ACTION's value of your form statement is incorrect http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 11 of 20


name

11/3/10 9:47 AM

Here is the example displayed. Click on the submit button of the form to see the error message and look at the URL of the error message. Also view source for the form and check the ACTION's value of the form statement. (Note that cgi-wrap is incorrect)

Debugging Fix: correct the ACTION's value Example 4: Reason for error: error in your Perl script Here is the example displayed. Click on the submit button of the form to see the error message.

Debugging Fix: Check your Perl script for error(s) and correct them The best way that I have found to find this error is to connect (using SSH) to your hills account and run the Perl interpreter on your script. Go to your cgi-bin subdirectory by entering: cd public_html/cgi-bin perl testerr4.pl (where testerr4.pl is the name of your Perl script) You should now be able to locate the error in your perl script. In this example, the Perl script had primt "Content-type: text/html\n\n"; Here is what the Perl interpreter found: String found where operator expected at testerr4.pl line 12, near "primt "Content-type: text/html\n\n"" (Do you need to predeclare primt?) syntax error at testerr4.pl line 12, near "primt "Content-type: text/html\n\n"" Execution of testerr4.pl aborted due to compilation errors.

NOTE: There is an alternative to using unix for finding Perl script errors. It involves changing your form ACTION to: <form action="/cgi-bin/cgiwrapd/srubin/form1.pl" method="Post"> Then use your browser to submit the form that utilizes a Perl script that has an error. (Note the use of cgiwrapd)

Example 5: Reason for error: error in your Perl script Here is the example displayed. Click on the submit button of the form to see the error message. http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 12 of 20


name

11/3/10 9:47 AM

Debugging Fix: Check your Perl script for error(s) and correct them To find this error: connect to your hills account and run the Perl interpreter on your script. Go to your cgi-bin subdirectory by entering: cd public_html/cgi-bin perl testerr5.pl (where testerr5.pl is the name of your Perl script) You should now be able to locate the error in your perl script. In this example, the Perl script had &ReadParse instead of &ReadParse; Here is what the Perl interpreter found: syntax error at testerr5.pl line 12, near "print" Execution of testerr5.pl aborted due to compilation errors NOTE: this error is harder to find since it gives an error on the line after the actual error.

Example 6: Reason for error: error in your Perl script Here is the example displayed. Click on the submit button of the form and this time the script apparently works, since some output is returned. But noticed that the first line of output is incomplete.

Debugging Fix: Check your Perl script variable name and the the corresponding variable name in your form. You should see that they do NOT match. Fix this error by changing either variable name so that they DO match. Example 7: Reason for error: the Perl script was incorrectly uploaded in binary mode Here is the example displayed. Click on the submit button of the form to see the error. The error message actually mentions: "This message usually indicates there is a problem with the script itself. Often this indicates either that the #! line of the script is incorrect, or the script was uploaded in binary mode instead of ascii mode." Check to make sure that the script does not have control-M's at the end of every line. That will prevent it from executing. An easy fix that takes care of this most of the time is to put '#!/.../perl --' instead of '#!/.../perl' on the first line of the script. This is typically a problem if the script was edited or uploaded from a DOS/Windows/Macintosh station to a unix based server.

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 13 of 20


name

11/3/10 9:47 AM

Debugging Fix: Upload the script in ascii mode.

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 14 of 20


name

11/3/10 9:47 AM

Introduction to PHP What is PHP? It's official name is PHP: Hypertext Preprocessor, and it is a server-side scripting language. When your Web browser accesses a URL, it is making a request to a web server. When you request a PHP page, for example, http://fog.ccsf.edu/~srubin/formA.php, the Web server wakes up the PHP parsing engine and says, "Hey! You've got to do something before I send a result back to this person's Web browser." Then the PHP parsing engine runs through the PHP code found in formA.php, and returns the resulting output. This output is passed back to the Web server as part of the HTML code in the document, which in turn is passed to your browser, which displays it to you.

What does PHP do? Here are some common uses of PHP: Perform system functions: create, open, read from, write to, and close files on your system; execute system commands; create directories; and modify permissions. Gather data from forms: save the data to a file, send data via e-mail, return manipulated data to the user. Access databases and generate content on-the-fly, or create a web interface for adding, deleting, and modifying elements within your database. Set cookies and access cookie variables. Start sessions and use session variables and objects. Use PHP user authentication to restrict access to sections of your web page. Create images on-the-fly. Encrypt Data.

The Form statement and PHP directory: http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 15 of 20


name

11/3/10 9:47 AM

In Homework 8b, you are to create a form and a php script for processing the form, namely, (1) to send the form information from the user back to you in an email, and (2) to return the form information back to the user's screen as a verification that the email has been sent. The form is a normal HTML page with form elements. The form statement should contain an action equal to your php filename along with a method of post. For example: <form action="formA.php" method="post"> For the Hills server: Your php file must reside in a directory, called php, which is a sub-directory of your public_html directory. The php directory should have a unix permission of 711, that is, read permission for owner and execute permission for owner, other, and group. A permission of 755 will also work. Be sure to upload your php file in ascii transfer mode. Regarding the form statement, notice that the action's value does not refer to your php directory, because the server will know to automatically look in the php directory for any files having a file extension of .php. You must NOT include the reference to the php directory in the path; the special cgiwrap that Apache uses when it sees the .php extension presumes that directory implicitly. Note that other servers may not require your php files to be in a special sub-directory called php. Please Note: your php directory should be directly within your public_html directory. If your hw8b.html has as its URL: http://hills.ccsf.edu/~USERID/cnit132/hw8b.html then the php directory is 1 directory up from hw8b.html and your form statement would be: <form action="../formA.php" method="post"> If your hw8b.html has as its URL: http://hills.ccsf.edu/~USERID/cnit132/homework/hw8/hw8b.html then the php directory is 3 directories up from hw8b.html and your form statement would be: <form action="../../../formA.php" method="post">

The PHP script to email your form and return a screen verification: Your PHP script must have a file extension of .php. Here is the content of my formA.php. <?php $msg = "E-MAIL SENT FROM FOG\n"; $msg .= "Sender's Name: $_POST[sender_name]\n"; $msg .= "Sender's E-mail: $_POST[sender_email]\n"; $msg .= "Sender's Age: $_POST[age]\n"; $msg .= "Message: $_POST[message]\n\n"; http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 16 of 20


name

11/3/10 9:47 AM

$to = "srubin45@comcast.net"; $subject = "Form Feedback from Fog"; $mailheaders = "From: $_POST[sender_email]\n"; $mailheaders .= "Reply-To: $_POST[sender_email]\n\n"; mail($to, $subject, $msg, $mailheaders); ?> <html> <head> <title>The following email has been sent to Steve Rubin</title> </head> <body bgcolor="#f5f5dc"> <p><b>Your Name: </b> <?php echo "$_POST[sender_name]"; ?> <br /><br /> <b>Your E-mail Address: </b> <?php echo "$_POST[sender_email]"; ?> <br /><br /> <b>Your Age: </b> <?php echo "$_POST[age]"; ?> <br /><br /> <b>Your Message:</b> <?php echo "$_POST[message]"; ?> </p> </body> </html>

Explanation of the above code: The code in formA.php will send an email back to you and and return the form information back to the user's screen. A. Begin a PHP block and start building a message string: <?php $msg = "E-MAIL SENT FROM FOG\n"; NOTE: The message E-MAIL SENT FROM FOG will be the first line in the message text of the email that is sent and can be changed to anything you like. \n is a carriage return. B. Continue building the message string by adding an entry for the sender's name: $msg .= "Sender's Name: $_POST[sender_name]\n";

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 17 of 20


name

11/3/10 9:47 AM

NOTE: The .= indicates concatenation. Your variable after $_POST must match exactly the variable name in your form input text box for sender's name. For example in my HTML form page, I have: <input type="text" name="sender_name" size="40"> NOTE: You don't have to use the variable sender_name in your form or in this php file. What matters is that the names must MATCH. C. Continue building the message string by adding an entry for the sender's e-mail address, an entry for age, and an entry for the message: $msg .= "Sender's E-mail: $_POST[sender_email]\n"; $msg .= "Sender's Age: $_POST[age]\n"; $msg .= "Message: $_POST[message]\n\n";

NOTE: The extra spaces before $_POST are there so that the messages will be better aligned vertically when you are reading the email. The variable names after $_POST (in this case, sender_email, age, and message) must match exactly the variable name in your form input text box, radio buttons, and textarea. For Example, in my HTML form page, I have: <input type="text" size="25" name="sender_email" /> <input type="radio" name="age" value="0-20" />Under 21 <textarea rows="5" cols="20" name="message"></textarea>

D. Create a variable to hold the recipient's e-mail address (substitute your own): $to = "srubin45@adelphia.net";

E. Create a variable to hold the subject of the e-mail: $subject = "Form Feedback from Fog";

NOTE: You can change the string inside the quotes to anything you like. F. Create a variable to hold additional mailheaders: $mailheaders = "From: $_POST[sender_email]\n";

NOTE: This will put the sender's email address in the from field of the sent email that comes to you. Note also that the variable name inside of the square brackets must match exactly the variable name http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 18 of 20


name

11/3/10 9:47 AM

in your form input text box for sender's email address. G. Add to the $mailheaders variable: $mailheaders .= "Reply-To: $_POST[sender_email]\n\n";

NOTE: the variable name inside of the square brackets must match exactly the variable name in your form input text box for sender's email address. H. Add the mail() function: mail($to, $subject, $msg, $mailheaders);

I. Close your PHP block: ?>

NOTE: You're not done yet. Although this code will send the email, you should return something to the user's screen so that they know the form has been sent. Otherwise, they might sit there and continually click the Send button. J. The next 6 lines are normal HTML statements. K. Add the text label for the Your Name field and display the user's input: <p><b>Your Name: </b> <?php echo "$_POST[sender_name]"; ?>

NOTE: sender_name must match exactly the variable name in your form input text box for sender's name. <?php echo "$_POST[sender_name]"; ?> returns to the screen the value of that form name variable. L. Add the text label for the Your E-mail Address field and display the user's input: <b>Your E-mail Address: </b> <?php echo "$_POST[sender_email]"; ?>

NOTE: sender_email must match exactly the variable name in your form input text box for sender's email.

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 19 of 20


name

11/3/10 9:47 AM

M. Add the text label for the Age field and display the user's input: <b>Your Age: </b> <?php echo "$_POST[age]"; ?>

NOTE: age must match exactly the variable name in your form input text box for sender's age. N. Add the text label for the Message field and display the user's input: <b>Your Message:</b> <?php echo "$_POST[message]"; ?>

NOTE: message must match exactly the variable name in your form textarea for message. O. Add the closing HTML statements.

PHP Tutorials: http://us2.php.net/tut.php http://www.w3schools.com/php/default.asp http://www.freewebmasterhelp.com/tutorials/php

http://insight.ccsf.edu/mod/book/print.php?id=136109

Page 20 of 20


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Book 9: JavaScript Book for Weeks 16-18:

JavaScript

Site: Insight @ CCSF Course: CNIT-132-META-Intermediate HTML & XHTML-Rubin-Fall 2010 Book: Book 9: JavaScript Printed by: Donald Siino Date: Saturday, 6 November 2010, 12:56 PM

1 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Table of Contents 1 Introduction to JavaScript 2 Programming Overview: Terms and Concepts 3 Variables: An Introduction 4 Variables: Data Types 5 Typed and Untyped Languages and Simple Variable Operations 6 JavaScript Objects and Functions: An Overview 7 JavaScript Objects and Functions: Part Two 8 Event Handlers and the javascript Absolute URL 9 The SCRIPT Tag 10 Basic Function Syntax 11 Variables: Local and Global 12 Local and Global Variable Naming Conventions 13 Functions: Declaring Arguments 14 Opening a New Window 15 Common Event Handlers 16 Operators 17 Logic: A Simplified Overview 18 Logic: A Simplified Overview, Part Two 19 The window.open() Method Revisited 20 The return Keyword 21 Form Pulldown Menus Used as Navigation Elements 22 Simple Debugging Techniques for JavaScript 23 Some Final Thoughts about JavaScript

2 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Introduction to JavaScript Today, virtually every major website uses JavaScript, also called ECMAScript, to enhance the functionality of HTML pages. Image-switching buttons, e-commerce shopping carts, forms processing functions, even the new Flash and Shockwave movies, require the use of JavaScript programs. To one degree or another, every web designer today MUST be able to use JavaScript, even if it is only to copy and modify someone else's code to use in a new webpage. Because almost every site today uses JavaScript, it is important that YOU possess at least a rudimentary knowledge of JavaScript and the fundamentals of computer programming as they apply to JavaScript. Many of the JavaScript scripts used in today's websites are fairly simple; this is not likely to remain true for long, however, as many cutting-edge technologies (Dynamic HTML, Flash, and others) rely on JavaScript programming to unlock their full potential. Unfortunately, not everyone can really learn to program successfully; if everyone could do it, companies wouldn't pay programmers such huge sums of money. Still, you must learn at least a little JavaScript in order to survive in today's competitive Internet marketplace. In this module, I will endeavor to explain the concepts behind JavaScript and programming in general. This module is not intended to substitute for a full-length programming class; instead, they should introduce you to JavaScript programming concepts enough to get you prepared for more in-depth course work. A full examination of JavaScript is the next course, CNIT 133. For this class, you are NOT required to write any JavaScript elements from scratch. Much of what you do in Homework 9 is to copy and modify already existing scripts from my Homework 9 Sample Web Pages or from the textbook. We are now entering a more complex, more technical, environment which I will do my best to de-mystify and explain. I will be giving you as much detail as I can without obscuring the meaning of my explanations. This module is intended both as an introduction to programming, and as an explanatory reference for certain key aspects of JavaScript.

3 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Programming Overview: Terms and Concepts Up to this time, you have programmed solely in HTML and CSS, which are DECLARATIVE languages; they declare what something is (HTML) and what that something is supposed to look like (CSS). If you actually want something specific to happen on a web page (such as opening a new window or processing a form), you will need to use an IMPERATIVE language, a language that says "do this!", a language, in short, like JavaScript. Simple activities in JavaScript, like opening a new window or creating custom status bar messages, require minimal programming expertise; scripts for these sorts of things can be had in any decent JavaScript "cookbook". The purpose of these lectures is to present an overall concept of programming in JavaScript which will give you a foundation, upon which you can build, to permit you to go beyond the simple scripts. In JavaScript, a program, called a FUNCTION, is a collection of lines of text-based code which performs some activity. JavaScript is an "event-driven" programming language, which means that functions in JavaScript are triggered by events. What is an EVENT? An event, in JavaScript, is any user interaction with the computer. Clicking the mouse is an event. Pressing a key on the computer keyboard is an event. Moving the mouse around on the screen is an event. Loading an HTML page in the browser is an event. Any action initiated by the user constitutes an event. You already know what a RESOURCE is: a resource is any piece of digital media, whether text, sound, graphic, animation, form element, or CSS document, among others. Think beyond your current definition of resource. Resources can include individual pieces of code, functions, windows, dialog boxes, scrollbars, interface elements, etc. Almost anything in the computer, anything digital, can potentially be a resource which you may then access and/or manipulate in JavaScript. When you are programming in JavaScript, you will write FUNCTIONS which are triggered by user-initiated EVENTS; these functions will, in their turn, access and manipulate RESOURCES for various purposes. In other words, the user will interact with the computer, triggering a JavaScript program; that program will do something, then use resources to display something for the user to see, hear, or experience (this is called FEEDBACK). You, as the programmer, are designing the feedback for the user, as well as figuring out how the program itself is supposed to work. You have to design every aspect of the user experience or USER INTERFACE, the user interface being that portion of the program which the user will interact with that includes both interface elements (such as buttons and text fields) as well as feedback (such as dialog boxes, screens, sounds, etc). When you are programming in JavaScript, you need to ask yourself what YOU would expect if you were using this device. Would it beep? Would the buttons hilite as you clicked them, and would you want to see rollover effects (like active/inactive button states)? What kind of response would you expect from the computer once the program is finished executing? Would 4 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

you want to see dialog boxes? Should the HTML page advance to a new page? Should a window open? And what would really IRRITATE you? What do you want to make sure DOESN'T happen? You, as the programmer, must define every aspect, every detail, of the UI (User Interface), including every aspect of how it behaves. But remember that old adage, KISS: "Keep It Simple, Stupid!" Don't include flashy highlights and rollovers that distract from the functionality of the program. A good interface is almost invisible, assisting the user without being obtrusive. Having said all of this, the user interface is, in some respects, merely the clothing on the living creature of your program. The real flesh and bone of a program lies in the calculations, the operations, the decisions being made by the program itself which actually do the task at hand. You can obsess about what your buttons are going to look like, or what your dialog boxes are going to say, until your hair falls out, but if you haven't got code inside of your program deciding something or solving something or calculating something or moving something around, you're not going to have anything useful in the end. Imperative programming languages, such as JavaScript, C/C++, and Java, use something called LOGIC to make simple decisions and perform repetitive actions in a program. In addition, these languages use OPERATIONS to perform mathematical calculations, comparisons, transfers of data, and other activities within the computer itself. In combination, logic and operations do all of the actual work inside of a program. How logic operates, and what sort of operations JavaScript is capable of, are topics for discussion in later sections. All that you have to remember right now is that computers are really very stupid creatures; they can't do anything for themselves unless you tell them how to do it, which means that you have to spell EVERYTHING out for them. In addition, the operations and decisions computers can make are really very simple ones compared to the ones humans can make; sophisticated programs create an ILLUSION of complex behavior by layering many simple operations together and performing them at unbelievably high speeds. At the core of any program, however, are basic logic structures and basic operations which we will introduce in these modules. Computer programming is mostly comprised of problem solving: taking large complex problems, breaking them down into the smallest possible pieces, and building programs out of these simple bits. Whenever students ask me how to tackle a problem, I always respond that they should WRITE DOWN the things that they are sure about, even the stupidest-seeming things. Once you have written down things you KNOW must happen or problems you have already solved, it makes it much clearer what remains to be done. In addition, you must start breaking down your problems into the simplest bits that you can think of, until you have the entire problem broken down into single tasks which the computer can perform. I will attempt to explain a little more about this process in the next module.

Summary In JavaScript, user-initiated EVENTS trigger JavaScript FUNCTIONS. These functions 5 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

contain LOGIC which makes decisions or performs repetitions, using OPERATIONS to calculate, to compare, or to solve various problems. Once all logic and operations are finished, the function accesses and/or manipulates RESOURCES to generate user FEEDBACK based on the decisions and operations it has made. Obviously, this is an artificially simplified statement (since logic, operations, resources, and functions would actually be a part of ALL of these processes), but it gives you a GENERAL idea of the process involved in the execution of a JavaScript program. You, as a programmer, will design every aspect of the JavaScript code itself, as well as the USER INTERFACE. You will be taking complex problems, breaking them down into single tasks which the computer can execute, and reassembling these simple bits into larger-scale programs which can then perform the complete task.

6 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Variables: An Introduction A computer stores data, among other things. The term "data" sounds intimidating, but it really isn't. Data is simply information. On the computer, data can be numbers, or words, or pictures, or sounds, or movies, or anything. When you program in any imperative programming language, you will need to instruct the computer when to store data, and when to transfer data, and when to delete data, etc. Data, however, can be much more than mere information; it can also be references to actual elements of the web page or the web browser itself. You'll see what I mean as we go along. In imperative programming languages, such as JavaScript, data is stored in VARIABLES. A variable is really just a container for information, for data. In JavaScript, ANYTHING can be stored in a variable. A number or a word could be stored in a variable. A picture or a sound file could be stored in a variable. Even a reference to an actual browser window or an entire HTML page could be stored in a variable in JavaScript, allowing you to open or close (or otherwise manipulate) that browser window (for instance), or even alter an individual HTML element in that browser window, via the appropriate JavaScript variable. After we have explored some more basic JavaScript programming concepts, I will show you how variables and actual browser elements work together. Until I have given you some more theoretical information about programming, however, none of my explanations of the practical applications would make any sense, so please bear with me. Think of a variable as if it were a box. You take data and you put it into a box (a variable). You can also replace the data in one of these variable boxes with new data. A variable MUST have a name; otherwise, you'll have no way to refer to that variable in a manner which the computer (or YOU) can understand. In JavaScript, names ARE case-sensitive (along with everything else), so SPELLING COUNTS! Variable names follow the standard naming conventions we have discussed in earlier modules, and should usually begin with a lower-case letter. In the following example, I will create a variable called "george". I am going to fill george with a number, the number 1. Here is a conceptual picture of george:

7 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

As you can see, george, the variable, is a box with a name, containing the number 1. In JavaScript, you will use variables to store all data, whether it be numbers, or words, or pictures, or whatever.

Declaration and Initialization When creating variables in an imperative programming language, there is a two-step process: 1) declaration (declaring a variable), and 2) initialization (initializing a variable). Again, these technical words sound intimidating, but they're not. When you DECLARE a variable, you tell the computer that that variable exists; you also tell it what that variable's name is. When you INITIALIZE a variable, you fill that variable with data for the FIRST time (initial = first), setting it to its initial, or beginning, state. Computers are stupid. If you don't tell them that something exists, they can't figure it out for themselves; that's why you have to declare a variable. In JavaScript, you would declare "george" (from the above example) like this: var george;

To declare a variable in JavaScript, you must first state the JavaScript keyword, "var" (which tells the computer that you want to create something of type "var" or variable), followed by a space, followed by the name that you want to call that variable (in this case, the name is george); the command is finished off with a semi-colon to end the line of code. Once you have declared a variable, you may refer and make changes to that variable simply by stating its name and performing OPERATIONS upon it. Most operations in JavaScript (including addition (+), subtraction (-), multiplication (*), and division (/), among others) are performed with a handful of symbols, many of which will be already familiar to you; I will talk more about these OPERATORS a little later. In JavaScript, I could initialize the already-declared variable, george, using the following syntax: george = 1;

8 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

In the above example, I have initialized the variable, george, setting it equal to the number 1; I have done this using the "gets" operator, which is represented by the equals (=) sign. The "gets" operator (=) replaces the contents of whatever is on its left-hand side with whatever is on its right-hand side. In the above example, george "gets" 1; this means that the "gets" operator takes the number 1 from its right-hand side and sticks that value into george on its left-hand side, replacing george's contents; since george has never contained any data, this process INITIALIZES george, setting him to a starting value of 1. Again, I have ended my command, my line of code, with the semi-colon end-of-line marker; every complete command in JavaScript must end its line with a semi-colon. A COMMAND is an instruction or set of instructions for the computer, telling it to do something (or multiple somethings). Every time you come to the end of a command in JavaScript (which will end a line of code), you must mark the end of that line with a semi-colon, as in the above examples. I could also declare and initialize the variable, george, in a single step using the following syntax: var george = 1;

First, I declare george to exist by using the var keyword, then I use the "gets" operator to initialize george to contain the number 1. Although it is possible to combine these two processes (declaration and initialization) together into one command as in the above example, it is important for you to understand that these are two separate actions, and that there will be times when you will NEED to separate variable declaration and initialization for one reason or another.

A Note on Semi-Colons JavaScript is derived from the programming language called "C". All C-based languages end lines of code with semi-colons; a semi-colon (;) is the end-of-line or end-of-command marker. You have already seen a similar use of the semi-colon in CSS, where a semi-colon marks the end of a property definition (i.e. font-size:24px;). Note: Older code written in JavaScript does NOT always use a semi-colon to mark the end of a line of code. Theoretically, JavaScript, under many circumstances, may count carriage-return characters as a replacement for semi-colon characters; this does not always work properly, however. I cannot recommend the omission of semi-colon characters when coding commands in JavaScript, as it opens you up to unexplained errors due (I assume) to bugs in the JavaScript interpreters.

9 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Variables: Data Types As mentioned earlier, variables can contain many kinds of data or information. There are several official TYPES of data which JavaScript can understand. In brief, I am going to outline a few of the most important of these data types, since I will be referring to them when we start coding a little later. In JavaScript, there are three essential "primitive" data types: numbers, strings, and booleans. Here are some numbers: 10 -147 .0035 1.5 -520.0003

As far as JavaScript is concerned, numbers may be positive or negative, and may have decimal places or be without decimal places. As I mentioned earlier, however, JavaScript is a C-based language; the C-based languages include C++, Java, and JavaScript, among others. In C-based languages, numbers are divided into two separate varieties: integers (int) and floats (float). Integers (int) are whole numbers with NO decimal places. Here are some integers: 1 -100 247 -68000 0

Floats (float) are numbers WITH decimal places. Here are some floats: .0003 146.5 -2.575 10000.1

Again, when you are programming in JavaScript, you will not usually differentiate between integers and floats. However, JavaScript DOES recognize a difference between integers and floats, and it has a few built-in features which allow you to manipulate numbers as either one or the other. STRINGS are collections of alphanumeric characters. Anything you can type on a computer keyboard may potentially be part of a string. Strings, in JavaScript, are always marked with quote marks. Here are some strings: "Hi" "Wow, you have 2.5 children!" "Michael"

10 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 "Hey, dude, I like your green hair..."

As you can see, strings are ALWAYS enclosed in double-quote marks, and may contain a variety of characters, whether text, numbers, spaces, or punctuation. In HTML, you have already dealt with strings frequently. Every time you set an attribute for a tag, you are actually setting that attribute equal to some string value (i.e. src="capitalA.gif" or width="54"). Even though strings may have numbers contained within them, there is a distinct difference between string-based numbers and actual numbers. For instance, these two values are NOT the same: 1 "1"

The first example is the actual number, 1. The second example is the CHARACTER "1", which is NOT a number; rather, it is merely a symbol that you type on the computer keyboard. You can NOT perform mathematical computations on a STRING "1", whereas you CAN perform mathematical computations on a NUMBER 1. Having said this, JavaScript has on-the-fly conversion capabilities which automatically convert string numerical characters to numbers, as well as numbers to strings, under appropriate conditions. Although this sort of automatic conversion is a tremendous convenience, it does NOT keep variables from being EITHER numbers OR strings at any given time; you will frequently be called upon to differentiate between these two data types in your code. I myself have been tripped up more than once by these on-the-fly conversions while programming in JavaScript, so I just wanted to make sure that I mentioned this feature. The third "primitive" data type in JavaScript is BOOLEAN. Booleans sound very technical, but they are quite simple. Invented by George Bool in a previous century, boolean numbers, in JavaScript and other traditional programming languages, have just two states: false and true, 0 and 1, off and on. The values of false, 0, and off are all equivalent, while the values of true, 1, and on are also equivalent. In JavaScript, booleans will always be either false or true (not off/on or 0/1). Booleans are everywhere in computer-based or electronics-based equipment. Have you ever noticed the | and 0 characters printed on the on/off switches for your computer, stereo, or other pieces of electronics equipment? Those characters represent on and off for the switch, with | or 1 being ON, and 0 being OFF. That's a BOOLEAN! Switches themselves are firmly embedded in the history of the first computers. Once upon a time, computers were just gigantic, room-sized banks of switches, and, later, switches and lightbulbs, which turned on and off mechanically; when a lightbulb or switch was on, that was a 1, whereas when a lightbulb or switch was off, that counted as a 0. Using these 0's and 1's, you could create BINARY code (binary means numbers in base 2, which is all 0's and 1's). Just like the secret codes you may have played with as a child, you could say that the

11 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

number 0 represents the letter "a", and that the number 1 represents the letter "b", and that the number 10 (10 in binary is 2 in our regular counting system) represents the letter "c", and that the number 11 represents the letter "d", etc. With big enough binary numbers, you could extend your binary "secret code" to represent not only letters, but also colors, or sound waves, or picture information, or whatever you like. Once you have decided which binary numbers represent which characters or sounds or pictures, you could store this binary information in your computer. With the "key" to your binary "secret code", you could then take this binary information out of your computer, manipulate it in some fashion, convert it back into a semblance of its original form, and display, play, or printout this media. Using switches and lightbulbs, of course, computers could only store and manipulate a VERY limited amount of binary information (it took roomfuls of switches just to get enough numbers together to add up your checkbook, let alone represent millions of colors!); those early computers also weren't very fast. Now, with silicon microchips and advanced magnetic memory, computers can store and manipulate mind-boggling quantities of information at magical speeds. All of this data, however, is still encoded, stored, and manipulated in the computer using on/off, binary, BOOLEAN states. Although you will probably never have to get deep enough into the computer to be forced to look at actual binary conversion of data (thank goodness!), JavaScript, naturally enough, is still heavily reliant on booleans and boolean states. You will frequently be testing conditions in code to see whether something is true or false, a boolean state. Has the user clicked on a particular button? That information would be either true (the user HAS clicked on the button) or false (the user has NOT clicked on the button), a boolean state. Has the user visited this page three times? If they HAVE visited the page three times, the condition would be TRUE, whereas if they have visited the page FEWER than three times or MORE than three times, the condition would be FALSE, another boolean state. In some kind of game code, you might have a boolean variable which remains false until the user has collected all of the "magic wands" in the game (for instance), whereupon the boolean variable would be changed to true, allowing new levels of the game to open up. Boolean variables are everywhere in JavaScript. Besides the three "primitive" data types, there is also the OBJECT data type in JavaScript. Objects include a whole host of structures and entities which are beyond the scope of this introductory lecture. In the next section, however, we will discuss the basic features of generic objects, as you will need to know a little bit about objects in order to use JavaScript effectively (since almost everything in JavaScript is built using objects). Beyond the primitive data types, and objects, there are two more data types you should be aware of: null and undefined. The variable that is null contains NO information. You should know, however, that null is NOT 0; Zero (0) is an integer, a number. The null variable is empty. In JavaScript, the null variable is differentiated from the undefined variable. An undefined variable has not been declared, and therefore does not exist, or has not been initialized, and so contains no data. 12 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

You will find that there are many times when you will need to check for the null or undefined variable data types, especially when handling user feedback or input. For instance, if you program JavaScript to bring up a prompt window (which allows a user to type in some information and click either the OK or Cancel buttons), you will need to test for the undefined or null variable if a user has not given any input or has pressed the "Cancel" button on the prompt dialog box; this is just one place where you might need to test for this data type. The null variable and the undefined variable may be treated interchangeably in JavaScript, but can be detected individually in the most modern browsers, if needed. There are many other data types, but they are beyond the scope of this class. For more information on data types, refer to "JavaScript: The Definitive Guide", Chapter 3.

13 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Typed and Untyped Languages and Simple Variable Operations In JavaScript, variables may contain ANY type of data. When you declare a variable, you only need to state the keyword var and the name of the variable; this creates a generic variable. Once you have a variable declared, you can stick a number or a string or a boolean or an object into the variable, and change the data type of the variable at will. Example: var george = 1; george = "Hi";

In the above example, I have set george equal to the number 1. In the second line of code, I have replaced the contents of george with a string, "Hi". I have changed george's data type from a number to a string. This kind of action is possible because JavaScript is an "untyped" language. In an untyped language, a variable may be of any data type, and an individual variable's data type may be changed at any time. Most programming languages, like C++ and Java, are "typed" languages. In a typed language, a given variable may only ever be ONE data type. For instance, in C/C++, you would create an "int" variable type, and that variable could only contain an integer, or you would create a "string" variable type, and that variable could only ever contain a string. Example (C/C++): int george = 1; string fred = "Hi"; float ethel = 1.052;

In the above example in C/C++, I have declared and initialized three different variables. The variable george is an integer (int) and may only ever contain an integer. The variable fred is a string, and may only ever contain a string. The variable ethel is a float, and may only ever contain a number with decimal places. In typed languages like C/C++, variable data types remain fixed for the duration of a program. As I mentioned earlier, even though JavaScript is an untyped language, and even though you can change a variable's data type on-the-fly in JavaScript, variables can only be a SINGLE data type at any given time, whether that type be a number, a string, a boolean, an object, or null/undefined. Here are some more JavaScript examples of variables being declared, initialized, and otherwise operated upon: var var var var

14 of 71

kate = "hi"; louie = 10.25; josie = louie; sam = 200;

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 var answer = louie + josie + sam; kate = answer;

In order of the examples: the variable kate now contains a string value, "hi". The variable louie now contains a number. The variable josie has been set equal to louie, which means that a copy of louie's contents have been placed inside of josie; both josie and louie, then, are equal to 10.25. The variable sam now contains a number as well. The variable called answer has been set to the sum of louie and josie and sam, which would be 10.25 + 10.25 + 200, or the number 220.5. Note: answer is just a random name, picked because it makes sense in English; I could have named it anything. The variable kate (which has already been declared), then, has had its string content of "hi" replaced with the numerical content of the variable answer, which changes kate's data type from a string to a number. The following example is WRONG: louie + josie + sam = answer;

Even though the above example looks like math operations that you might perform on paper, the above syntax is backwards. The variable answer needs to contain the sum of louie + josie + sam, which is only possible if the variable answer is on the LEFT-HAND side of the "gets" (=) operator (since the "gets" operator always replaces the contents of the left-hand variable with whatever is on the right-hand side). Left-to-right orientation, then, is important in JavaScript, as well as case-sensitivity! Example (CORRECT): var answer = louie + josie + sam;

The following example is ALSO WRONG: var answer = louie + JOSIE + Sam;

Earlier, I initialized the variables josie and sam using all lower-case letters in their names. Since JavaScript is case-sensitive, JOSIE and Sam represent different, non-existent, undefined variables. The variable answer in the above example, then, would end up containing non-valid information, producing a bug and a JavaScript error in your code. Again, I apologize for the abstractness of these examples, but you must understand the basics of JavaScript variable syntax before you can do anything at all with the language. I hope that you can see, though, that handling these variables and performing simple mathematical operations upon them is fairly straightforward as long as you understand the basic logic behind their syntax. Of course, you can do a lot more than mathematical operations with JavaScript; we'll get to a few simple, practical things before the end of this module.

15 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

JavaScript Objects and Functions: An Overview Because JavaScript is an object-oriented programming language, I need to tell you a little bit about JavaScript "objects" and the structure of the language generally, before we can actually start programming in JavaScript specifically. In any programming language, you write lines of code which are executed, left-to-right, top-tobottom, just like in HTML. In an object-oriented programming language such as JavaScript, however, much of this code is organized in OBJECTS. In fact, most of the built-in features of JavaScript use objects of one sort or another, which means that you need to understand basic object syntax before you can do much of anything, including reading the JavaScript reference books. In an HTML page in a JavaScript-enabled web browser, most or even all things on the page are mirrored in JavaScript objects. There is a window object which refers to the browser window itself, there is a document object which refers to the HTML page itself (and, potentially, everything contained in that HTML page), there is an images object which has to do with pictures, etc. By manipulating these objects in JavaScript code, you can affect the behavior and appearance of an HTML page, call up dialog boxes or other resources, and invoke a fairly sophisticated set of commands to do your bidding. Every object in JavaScript has two main components: a set of PROPERTIES, and a set of METHODS. Properties are generally passive in nature, describing the state of some feature of the object. Methods, on the other hand, are generally active, performing some sort of task. Over the years, I have used something called the "object-oriented car", a common metaphor in programming instruction, to explain object-oriented programming principles. As I have grown more sophisticated in my explanations, however, the "car" object example has begun to break down. Now, instead of describing the entire car in my lectures, I describe only the STEERING WHEEL of the car using object-oriented programming terms. Let us create a SteeringWheel object (and notice how the name of the object has NO SPACES!). This SteeringWheel object has one property, "direction", and one method, "honk()".

The direction property of the SteeringWheel object says what direction the SteeringWheel is pointed. Since this is a VERY simple SteeringWheel, only left, right, or center would be legal

16 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

values for this property. The honk() method of the SteeringWheel object honks the car's horn; we'll talk more about this method later on. The code that defines the SteeringWheel object, with all of its properties and methods, is called a CONSTRUCTOR. The exact syntax for creating your own object constructor is really beyond the scope of this introductory lecture. However, you WILL be invoking pre-built constructors when you use JavaScript, so we'll talk about how to do this. The SteeringWheel constructor merely defines the basic structure of the SteeringWheel object; it does NOT actually create a SteeringWheel which you can manipulate directly. To get a SteeringWheel object that you can use, you need to create an INSTANCE of the SteeringWheel object (also known as INSTANTIATING a SteeringWheel object). When you create an instance of an object, you are creating ONE copy of the object which you have control over. In JavaScript, you will need to instantiate an object by using a variable to contain a copy of the object. First, you'll declare a variable to hold the instance of the SteeringWheel object; then you'll initialize the variable as a "new" SteeringWheel object using the "new" keyword. Example: var theWheel = new SteeringWheel();

Whenever you instantiate an object, you MUST use the keyword, new, before the call to the object constructor, as you see above. Also, notice the opening/closing parentheses characters following the call to the SteeringWheel constructor (and prior to the semi-colon end-of-line marker); these parentheses are called the "function call" operator (which calls/invokes a function), and are an essential part of the object instantiation process. A FUNCTION, in JavaScript, is a collection of lines of code, a program, which does something (like switch an image, or pop up a new window, or BUILD AN OBJECT, etc). In order to execute a function, to make a function "run" in JavaScript, you must state the name of the function, followed by the "function call" operator (the opening/closing parentheses characters); this will cause the function to execute when your code is executed. Note: we'll talk about making our OWN functions a little later on in this module. It turns out that an object constructor, such as the SteeringWheel object constructor in the above example, is made in JavaScript out of a FUNCTION. The same function syntax that you will use to create miniature programs later on is also used to make object constructors! Just as a side note, it turns out that FUNCTIONS are also OBJECTS themselves; this is because almost everything in JavaScript is built out of objects. I'm sure that this seems confusing now, but don't worry about it; as you get deeper into JavaScript, over time, it will all start to make much more sense to you. Here's the code again:

17 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 var theWheel = new SteeringWheel();

Whenever you instantiate an object, you will DECLARE a variable, then INITIALIZE that variable to be a NEW instance of whatever OBJECT CONSTRUCTOR you want. An object constructor is really a FUNCTION, which you must execute in order to create your object; this is done by stating the name of the object constructor function (in this case, SteeringWheel), followed by the function call operator (the parentheses characters). Again, the function call operator is necessary in order to execute the object constructor function. As in all lines of code in JavaScript, you must end the line with a semi-colon end-of-line marker. Once you have created an instance of your desired object, you may access the PROPERTIES and METHODS of the object by using DOT SYNTAX. Dot syntax is a way of accessing child elements of a parent object (remember parents and children?) by using period/dot (.) characters between parent and child elements to indicate a path through a complex tree of relationships, much as the slash (/) character is used in URL syntax to indicate a path through a complex directory structure on a web server. Here's a much simpler example. If I wanted to put $10.00 cash into an empty cash register in my local coffee house in Guerneville, CA, USA, using JavaScript dot syntax to indicate the path to the cash register, the line of JavaScript code might look something like this: california.sonomaCounty.guerneville.cinnabarCoffee.cashRegister = 10;

Dot syntax always creates a path from the most general to the most specific element, reading from left-to-right, and, as you can see from the above example, there are NO SPACES IN THE NAMES of the elements or between the dots! Back to the instance of our SteeringWheel object, theWheel: The SteeringWheel object has one property, direction. Object properties can be accessed via the instance of the object using dot syntax. In the following examples, I am assuming that theWheel has already been declared and instantiated. Example: theWheel.direction = "left";

In the above example, I have set the direction property of theWheel object equal to the string, "left". Surprise! An object property is really a VARIABLE which is attached to a particular object; this property may be filled with whatever data we like (in this case, a string). Having executed the above line of code, theWheel is now pointed towards the left. Example: theWheel.direction = "right";

Now, theWheel is pointed towards the right. 18 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Note: At this point, students often point out to me that a property is supposed to be static, yet the direction property of theWheel seems to be turning the steering wheel of the car rather than merely reflecting which direction theWheel is pointing! Well, oftentimes object properties are not as static as I have led you to believe (remember, I said "usually" static!). In a real JavaScript object, however, I would probably have written a method called "turnWheel()" which actually turned the wheel, and the direction property would merely have been a string which indicated the current direction of the wheel. Please cut me some slack, I'm trying to make a simple example here! Now, if I wanted to honk the horn of theWheel, I would need to call the honk() method of theWheel. A METHOD is really a FUNCTION which is attached to an object, just as a PROPERTY is really a VARIABLE attached to an object (again, a function is a program which performs some action)! Therefore, I use the function call operator (opening/closing parentheses) after the name of the method (and dot syntax, of course). Example: theWheel.honk();

The above example executes the honk() method of theWheel, causing theWheel's horn to honk. Example (complete code): var theWheel = new SteeringWheel(); theWheel.direction = "left"; theWheel.direction = "right"; theWheel.honk();

Boy, if we drove like this down the road, we'd probably get a ticket for reckless driving! You can create more than one instance of an object, simply by declaring and instantiating more copies of the object. Example: var theWheel = new SteeringWheel(); var theSecondWheel = new SteeringWheel(); theWheel.direction = "left"; theSecondWheel.direction = "center"; theWheel.honk();

In the above example, there are two copies of the SteeringWheel object (hopefully attached to two separate cars!). The direction property of theWheel is set to "left", while the direction property of theSecondWheel is set to "center". Then, I honked the horn of theWheel, but I left theSecondWheel silent. Each instance of an object is separate, and contains separate information. Even though both 19 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

objects in the above example are SteeringWheel objects, they are completely independant from one another! I can make as many instances of an object as I want, but I think TWO SteeringWheel objects is enough for now...

20 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

JavaScript Objects and Functions: Part Two Let's look at a REAL example of JavaScript objects in action. In this example, I am going to instanciate two Image objects, which are used to represent GIF/JPEG pictures for use on a web page. I am then going to set the src (source) properties of the Image objects to appropriate URLs; these src properties are identical to the SRC attribute of an IMG tag. Example: var picture0 var picture1 picture0.src picture1.src

= = = =

new Image(); new Image(); "capitalA.gif"; "capitalB.gif";

Now, let's say that I have an IMG tag named "fred" on my web page. Example: <img src="capitalD.gif" width="54" height="54" name="fred">

I could access the image, fred, on my web page using something called the "simplified document object model", which allows me to use dot syntax to point to an element on an HTML page. Example (abbreviated): window.document.fred

Example (abbreviated; looking at SRC attribute of fred): window.document.fred.src

Example (full line of code): window.document.fred.src = picture0.src;

window is the instance of the Window object which represents the current web browser window. document is the instance of the Document object which represents the current HTML page in the web browser window. fred is the name of the IMG tag on the HTML page. src is the SRC attribute of the fred IMG tag. In the above example, I am setting the src property for fred equal to the src property of the picture0 Image object, thus changing fred's picture from a graphic of the letter D to a graphic of the letter A! I've just performed an image switch! Hooray! Now, I'm going to switch fred's image to picture1, the graphic of the capital letter B: window.document.fred.src = picture1.src;

Woowee! I've switched that image again! I'm programming in JavaScript, doing something 21 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

useful! Wow! Alright, so this is not ALL the code that you'll need to deal with image switching, but it outlines the basic principles. First, you instanciate image objects with src properties set to URLs for the images that you want. Then, you refer to the named IMG tag on the page using dot syntax and the simplified document object model, and reset the src property of the named IMG tag equal to the src property of the desired instance of the Image object. Almost every web site in creation uses image switching to make rollover effects on graphical hyper-references! Be warned, however: all images involved in a switch MUST have the same dimensions, the same width and height!

The SteeringWheel Object Revisited We need to talk more about the honk() method of the SteeringWheel object, to illustrate additional basic JavaScript programming principles. Our computerized car horn is capable of doing more than merely honking; it can play tunes, as well! There are two tunes it can make, along with the generic honk sound: Beethoven's Fifth Symphony Theme, and Mary Had a Little Lamb. Here are the string values representing these car horn tunes: "5th" for Beethoven's Fifth Symphony (dah dah dah DAAAAHHHH!). "MHALL" for Mary Had a Little Lamb. "honk" for the generic honking sound. Now, I need to pass these string values into the horn() method of the SteeringWheel object. To do this, I need to place the desired string BETWEEN the parentheses of the function call operator for the horn method in my JavaScript command. When you do this, you are said to be "passing a parameter" or "passing an argument" to the method. Example: theWheel.horn("5th");

In the above example, I am passing the string value "5th" as an ARGUMENT or PARAMETER (these words are often used interchangeably here) to the horn method of theWheel. This causes the horn in theWheel to play Beethoven's Fifth rather than the standard honking sound. Note: everything I say about parameters and arguments in this section may ALSO be applied to functions, since methods are really functions attached to an object! Let's have the horn play Mary Had a Little Lamb. Example: theWheel.horn("MHALL");

22 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Ah, what a sweet sound! By passing different arguments to a method, I can cause that method to behave in different ways. In JavaScript generally, you will pass ARGUMENTS or PARAMETERS for many different reasons and to many different effects. You can pass any data type you like as an argument to a method, whether it be number or string or boolean or whatever. Each built-in JavaScript method will require different sorts of arguments, and will perform different kinds of actions. Example: theWheel.horn(false);

I passed the boolean value, false, to the horn method. The way the horn method is written, a false value passed as an argument prevents the horn from honking. Many methods can accept boolean values of true or false in this way. Many methods are programmed to accept more than one argument. If you wish to pass more than one argument to a method, you must separate each argument with a comma (and an optional space, if you wish). Example: theWheel.horn("5th", "MHALL");

In the above example, the horn method first plays Beethoven's Fifth, then plays Mary Had a Little Lamb. Example: theWheel.horn("honk", "5th", "MHALL", "honk");

In the above example, the horn method plays a sequence of sounds, starting with a honk, moving to Beethoven's Fifth, then Mary Had a Little Lamb, and ending with another honk. In JavaScript, methods may accept one or more arguments, or a changeable number of arguments, depending upon how that method is written. Let's look again at our real world example, using the Image object. Example: var picture0 = new Image(54, 54);

It turns out that the Image object constructor can accept TWO arguments, both integers. The first argument represents the WIDTH of the image in pixels, while the second argument represents the HEIGHT of the image in pixels. These arguments initialize the width and height properties of the instance of the Image object in question.

23 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example: var picture0 = new Image(54, 100); var myWidth = picture0.width; var myHeight = picture0.height;

The variable myWidth is now equal to 54, which is the value of the width property of picture0. The variable myHeight is now equal to 100, which is the value of the height property of picture0.

One Last Note on Variables Variables are boxes for information. By stating a variable name in JavaScript code, you are passing or manipulating the information contained in that variable. Remember this example from a previous section? var louie = 10.25; var josie = louie;

By stating louie's name in the second line of code above, I was able to copy or pass the information from louie into josie by using the "gets" operator. In the same way, I can pass information from a variable into a method by stating the name of the variable between the parentheses of the function call operator. Example: var myHornSound = "5th"; var theWheel = new SteeringWheel(); theWheel.horn(myHornSound);

I just love to hear Beethoven's Fifth Symphony! Example: var myHornSound0 = "5th"; var myHornSound1 = "MHALL"; var theWheel = new SteeringWheel(); theWheel.horn(myHornSound1, myHornSound0, "honk");

In the above example, I passed THREE arguments to the horn method of theWheel; two of the arguments were variable names, and one was an actual string with no variable involved. Some of my arguments can be variables, while others of my arguments can be direct data; this is perfectly legal. The following example is NOT legal: var myHornSound = "5th"; var theWheel = new SteeringWheel(); theWheel.horn("myHornSound");

24 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Notice how I passed the STRING "myHornSound" to the horn method when I REALLY wanted to pass the variable named myHornSound? "myHornSound" is just a bunch of text characters, a string, while myHornSound is an actual call to the variable itself. The above code would break your JavaScript, since the horn method does not recognize the string, "myHornSound", as a legal argument value.

Summary A VARIABLE may hold an INSTANCE of an OBJECT. Each object has PROPERTIES and METHODS. Properties are essentially variables attached to an object, while methods are essentially FUNCTIONS attached to an object. A FUNCTION is a program which performs some action. Whenever you wish to execute a function (or a method), you must state the name of the function, followed by the FUNCTION CALL OPERATOR (which is represented by opening and closing parentheses characters). Properties and methods of an object are accessed using DOT SYNTAX, which allows you to trace the path of relationships between parent and child objects. Note: as you might expect, then, properties and methods of an object are child elements of the object. When you execute a method or function, you may pass ARGUMENTS or PARAMETERS to that method or function. Arguments/parameters passed to a method/function can influence the behavior of that method/function in some fashion. Data may be passed as an argument to a method/function either directly (by stating the actual number, string, or boolean value), or by passing a variable containing the data (by stating the variable name).

25 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Event Handlers and the javascript Absolute URL JavaScript is an event-driven programming language, where JavaScript commands are triggered by events caused by user interaction. JavaScript uses special EVENT HANDLERS inserted as ATTRIBUTES into ordinary HTML tags to access user events, such as clicking the mouse. Here is the event handler which deals with mouse clicks: onclick

As long as we are supporting older browsers, most event handlers MUST be placed into tags which can ordinarily accept mouse events, such as the A (anchor) tag, or the INPUT tag in a FORM. Here is the onclick event handler inserted into a hyper-reference: <a href="#" onclick="var george = 1;">Link Word</a>

The value of the onclick event handler attribute would be a JavaScript command of some sort. More than one command may be placed into an event handler in this fashion simply by appending commands onto the end of the previous command (don't forget your semi-colon end-of-line markers after each command!). Example: <a href="#" onclick="var george = 1; var fred = 2; var answer = george + fred;">Link Word</a> Before we get any deeper into this material, we need to look at the JavaScript Window object, which is built into every JavaScript-enabled web browser.

The Window Object When you open a JavaScript-enabled web browser, such as Firefox or Internet Explorer, certain built-in objects in JavaScript are declared and initialized automatically. One of these built-in objects is an instance of the Window object called window (with a lower-case "w"). Again, you do NOT need to declare the window instance of the Window object; this is done for you automatically when a web browser window is opened. The window instance refers to the current browser window, and has many properties and methods associated with it. A complete list of properties and methods of the Window object are printed in "JavaScript: The Definitive Guide", if you are interested. For the moment, I am only concerned with the alert() method of the Window object. The alert() method of the Window object causes an alert dialog box to open. Here is an 26 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

example of the alert() method in action: Alert Me The alert() method REQUIRES one argument, a string, which will become the text displayed in the alert dialog box. Technically, the alert() method is invoked with the following complete syntax: window.alert("Hi");

Because everything on an HTML page is displayed within the web browser window, however, it is NOT necessary to state the window instance name directly; window is automatically implied as the parent object for everything on an HTML page. It is perfectly safe to state the alert() method by itself, without using dot syntax to explicitly state the parent/child relationship between it and the window instance. The following syntax for calling the alert() method is perfectly safe and correct: alert("Hi");

Here is an example of the alert() method placed into an onClick event handler: <a href="#" onclick="alert('Hi');">Link Word</a>

Although in the previous examples, the string value passed as the argument to the alert() method was enclosed in DOUBLE-quotes, you can see that I have marked the string value in the above example using SINGLE-quote marks. I believe that we have encountered this problem in previous modules. Attributes may NOT have double-quote marks inside of the double-quote marks beginning and ending the value for the attribute, as this will break your HTML code. Because we NEED quote-marks of some kind to delimit the string value inside the function call operator for the alert method, we MUST use single-quote marks within the bounds of the double-quote marks marking the attribute value. When we write commands within ordinary JavaScript scripts, however, we will be able to go back to using double-quote marks to delineate string values; we'll talk about this later. Again, the following example would be WRONG: <a href="#" onclick="alert("Hi");">Link Word</a>

Those extra double-quote marks are EVIL. Corrected Example: <a href="#" onclick="alert('Hi');">Link Word</a>

You don't have to use the onclick event handler from within an A (anchor) tag. Instead, you can use the javascript absolute URL as the value for the HREF attribute in order to trigger JavaScript commands.

27 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example: <a href="javascript:alert('Hi');">Link Word</a>

In the above example, I have stated the SCHEME for the absolute URL (javascript), followed by the colon character, followed by the "scheme_specific_part", the actual JavaScript command desired. Note: When using the javascript absolute URL, you must NEVER have any spaces in your JavaScript code; otherwise, the javascript URL will fail to operate. The following example is WRONG because there are spaces in the URL: <a href="javascript:var fred = 1; alert(fred);">Link Word</a>

If your JavaScript command requires spaces (as in the above example), you MUST then use the onClick event handler rather than the javascript absolute URL. As I mentioned earlier, you do NOT have to put your onclick event handlers ONLY in A (anchor) tags; you may place the onclick event handler in ANY clickable tag, such as the INPUT tag in a form. Example: <form> <input type="button" value="Alert Me" onclick="alert('Hi There');" /> </form> Displayed

28 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

The SCRIPT Tag It must be evident to you now that event handlers (such as onClick) are inadequate for holding any substantive quantity of code. Most JavaScript code in a JavaScript-enhanced HTML page is placed within a SCRIPT tag. The main SCRIPT tag for a page goes in the HEAD of your HTML document. Between the opening and closing SCRIPT tags, you will write out your lines of JavaScript code. The SCRIPT tag has ONE attribute, TYPE. The TYPE attribute tells the browser which programming language is being coded inside of the SCRIPT tag. There are many different languages that can be coded within a SCRIPT tag; there are even several different versions of JavaScript itself. For this introductory class, all that you are concerned with is the main version of JavaScript. Tag: SCRIPT Attribute: TYPE Value: text/javascript Description: The TYPE attribute of the SCRIPT tag sets the programming language type to be coded within the tag. Example (abbreviated): <script type="text/javascript"> // Here's a couple of lines of JavaScript code: var george = 1; alert("Howdy"); </script>

Example (in context): <html> <head> <title>Sample JavaScript Page</title> <script type="text/javascript"> // Here's a couple of lines of JavaScript code: var george = 1; alert("Howdy"); </script> </head> <body> <p>Some content...</p> </body> </html>

In the above example, I have placed my SCRIPT tag in the HEAD of my HTML document. Between the opening and closing SCRIPT tags, I have programmed my JavaScript code, creating a variable called george containing a numerical value of 1, and calling the alert() method which is receiving one argument, the string "Howdy".

29 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Notice how I am able to use DOUBLE-QUOTE marks again to mark my string values? This is possible because I am NOT inside an attribute (as I was with onClick). Remember in our CSS module, when I talked about CSS comments? Single line comments were marked at the beginning of the line with "//", while multiple line comments were marked "/* comment... */". JavaScript, and all of the C-based languages, use the SAME commenting style! Unlike CSS, however, single line comment syntax IS supported in JavaScript, so you may use it with impunity here (as I did immediately following my opening SCRIPT tag). There is an older, deprecated attribute of the SCRIPT tag: LANGUAGE. You will still see many JavaScript-enhanced web pages using the LANGUAGE attribute of the SCRIPT tag rather than the TYPE attribute. Example: <script language="javascript"> <!-// Here's a couple of lines of JavaScript code: var george = 1; alert("Howdy") //--> </script>

It is no longer necessary to use the LANGUAGE attribute. Note: The <!-- right after the script tag and the //--> right before </script> are used to comply with older browsers that do not have javascript enabled. For the most part, they may be omitted. Note that some of my examples may include these statements. As an HTML page loads, the SCRIPT tag is executed, declaring and initializing variables, and executing methods. Example Code (abbreviated): <script type="text/javascript"> var george = 1; alert("Howdy"); alert(george); </script>

Example Code (in context): <html> <head> <title>Sample JavaScript Page</title> <script type="text/javascript"> var george = 1; alert("Howdy"); alert(george); </script> </head>

30 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 <body> <p>Some content...</p> </body> </html>

In the above example, I first declare and initialize a variable, george. I then call the alert method, passing the string value "Howdy" as an argument to the alert method. Last, I call the alert method again, passing the contents of the variable, george, to the alert method. Note: even though the contents of george are a NUMBER, not a STRING, JavaScript automatically converts the number INTO a string for use by the alert method. Cool, huh? Here is the above example displayed. Notice how the alert dialog boxes pop up as the page loads in the above example? As I said, the code inside the SCRIPT tag is executed as the HTML page loads. Of course, you're not usually going to want to have EVERYTHING in your script tag execute all at once; that would be complete chaos. To reserve some actions, and to call those actions at will rather than just as the page loads, requires the use of a FUNCTION. We'll talk about functions in the next section.

Final Notes An HTML page may, in fact, have several SCRIPT tags on it, both in the HEAD and in the BODY of the document. Because SCRIPT tags are executed as an HTML page loads, you may have a SCRIPT tag in the BODY of a page which lays on-the-fly HTML (built from JavaScript code) into the BODY of the HTML page as the page is parsing. The ramifications of this topic are outside the scope of this introductory lecture, but this sort of JavaScript usage is VERY common. JavaScript code may ALSO be coded into an external text file, called a ".js" file, which is very much like an external ".css" document, only filled with JavaScript code rather than CSS code. A ".js" file, or even several ".js" files, would be attached to an HTML page using the SCRIPT tag, and many HTML pages could share the same ".js" files. For more information, see "JavaScript: The Definitive Guide", section 12.2.2, pp.215-216. For example: <script src="abc.js"></script> Do not put the script tags in your external script files! Note that some scripts won't validate for XHTML unless you include /* <![CDATA[ */ right after the script statement and /*]]>*/ right before the closing script statement. <script type="text/javascript">

31 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

/* <![CDATA[ */ // content of your Javascript goes here /*]]>*/ </script> XHTML is subject to the same syntactical rules as XML. Because of this, an XHTML processor treats the characters < and & as markup, even if they reside inside a <script> block. see: http://javascript.about.com/library/blxhtml.htm

I suggest for all your scripts that you use: <script type="text/javascript"> /* <![CDATA[ */ // content of your Javascript goes here /*]]>*/ </script>

32 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Basic Function Syntax Inside a SCRIPT tag, you may define as many FUNCTIONs as you wish. A function is a piece of executable code, a program. A function can be triggered either by a call from an event handler, set in motion by a user, or by a call from another function. A function requires the following syntax: function doStuff() { };

First, you must state the JavaScript keyword, function, which tells the JavaScript interpreter that you want to create a FUNCTION. This is followed by a space, then the NAME of the function, followed by the parentheses characters (which are NOT, strangely, the function call operator here, but, rather, serve another purpose which we'll talk about a little later). The parentheses are followed by another space, then the opening and closing curly-braces we used in CSS; this is all ended, of course, with a semi-colon end-of-line marker. This statement of a function is called a FUNCTION DECLARATION. Note: the semi-colon end-of-line marker at the end of a function declaration is RARELY, or NEVER, seen, and is usually omitted entirely. Example (correct): function doStuff() { }

Between the curly-braces, then, we can define lines of code. In fact, just as in CSS, we will break out our lines of code, putting the opening and closing curly-braces on separate lines, and each line of JavaScript code between them on separate lines. Example: function doStuff() { var george = 1; alert(george); }

Again, this function would be placed inside of a SCRIPT tag. You may define as many functions as you like inside of your SCRIPT tag. Example: <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = 1; alert(george); }

33 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 function doSomethingElse() { alert("Howdy"); } /*]]>*/ </script>

White Space in JavaScript You will notice in the above examples that I have indented the lines of JavaScript code inside of the function declaration; this is a customary practice, and, unlike with HTML, it is supported and perfectly legal. Indent child elements (inside of curly-braces) one tab in from parent elements. As you can see in the above example, I have also used white space to separate my functions. This practice, too, is customary, supported, and legal. The one thing you have to beware of is placing CARRIAGE RETURN characters anywhere but at the ends of lines of code (or as blank lines). JavaScript can potentially interpret carriage return characters as SEMI-COLON end-of-line markers; if you put a carriage return in the middle of a command, the code may break. Example (WRONG): function doStuff() { alert( "Howdy" ); }

As you can see in the above example, I have placed illegal carriage returns in the middle of my function call operator, the parentheses. This will cause my code to break. Example (CORRECTED): function doStuff() { alert("Howdy"); }

Calling a Function from an Event Handler Once I have declared and defined my functions, I can call those functions from the event handlers or javascript absolute URLs in the BODY of my HTML page. Example (abbreviated): <a href="#" onClick="doStuff();">Link One</a> <a href="javascript:doSomethingElse();">Link Two</a>

Example (in context):

34 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = 1; alert(george); } function doSomethingElse() { alert("Howdy"); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff();">Link One</a></p> <p><a href="javascript:doSomethingElse();">Link Two</a></p> </body> </html>

Here is the above example. In the above example, do you notice how the code remains inactive UNTIL you click on the hyper-references in the BODY? When the user interacts with an HTML element, a function is called (from either an event handler or from the javascript absolute URL) and executed. Organizing our JavaScript code inside functions in the SCRIPT tag allows us to keep our HTML code relatively brief and uncluttered. It also opens up a door to a lot of power which is outside of the scope of this introduction to explore. I will mention again, however, that a function may be called from within ANOTHER function. Example (abbreviated): <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = 1; alert(george); doSomethingElse();

}

function doSomethingElse() { alert("Howdy"); } /*]]>*/

35 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 </script>

Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = 1; alert(george); doSomethingElse();

}

function doSomethingElse() { alert("Howdy"); } /*]]>*/ </script> </head> <body> <p><a href="javascript:doStuff();">Link One</a></p> </body> </html>

Here is the above example displayed. Notice how I only called the doStuff() function from within my event handler? The doStuff() function has been rewritten to call the doSomethingElse() function. So, from one event, I can call a function which can call many functions! I know that this doesn't seem like such a big deal to you right now, but it provides a means of writing the most sophisticated and powerful code imaginable. I can call both built-in JavaScript methods (such as the alert() method of the window object), and functions which I have defined myself! Pretty slick!

36 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Variables: Local and Global Variables come in two flavors: local and global. Local variables are temporary. A local variable is declared, initialized, and used for a short period of time, then thrown away. A local variable in JavaScript can only be used within a single function; no other functions have access to that particular variable; when a function is finished executing, the local variables for that function are thrown away. Global variables are persistent. A global variable is created when your web page is loaded, can be accessed by many different processes and functions, and lasts until your web page is unloaded from the browser window. Again, global variables last for the duration of your web page or program; local variables are used by one process or function, then thrown away. The distinction between local and global variables is very important in JavaScript programming. We will not have time to explore all of the ramifications of local and global variables in this brief introduction. However, I will be referring to local and global variables frequently in the upcoming sections. Global variables in JavaScript are declared at the base level of the SCRIPT tag. Example: <script type="text/javascript"> /* <![CDATA[ */ var george = 1; var fred = "Hi"; /*]]>*/ </script>

In the above example, both george and fred are GLOBAL variables because they have been declared at the base level of the SCRIPT tag. Global variables can be accessed within all functions. Example (abbreviated): <script type="text/javascript"> /* <![CDATA[ */ var george = 1; var fred = "Hi"; function doStuff() { alert(george); } function doSomethingElse() {

37 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 alert(fred);

}

/*]]>*/ </script>

Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ var george = 1; var fred = "Hi"; function doStuff() { alert(george); } function doSomethingElse() { alert(fred); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff();">Calling doStuff()</a></p> <p><a href="javascript:doSomethingElse();">Calling doSomethingElse()</a></p> </body> </html>

Here is the above example displayed. I can also change the contents of (or operate upon or manipulate) global variables from within functions. Example (abbreviated): <script type="text/javascript"> /* <![CDATA[ */ var george = 1; var fred = "Hi"; function doStuff() { alert(george); george = "Boo"; fred = "Howl"; } function doSomethingElse() { alert(fred);

38 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 george = "Yum"; fred = "Delicious!";

}

/*]]>*/ </script>

Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ var george = 1; var fred = "Hi"; function doStuff() { alert(george); george = "Boo"; fred = "Howl"; } function doSomethingElse() { alert(fred); george = "Yum"; fred = "Delicious!"; } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff();">Calling doStuff()</a></p> <p><a href="javascript:doSomethingElse();">Calling doSomethingElse()</a></p> </body> </html>

Here is the above example displayed. As you can see, each time we call one of the functions, we are changing the contents of the global variables. Try clicking the links a few times to see what I mean. Local variables are declared WITHIN a function declaration ONLY. Local variables will last only as long as the function is executing. When the function has finished executing, its local variables are thrown away. Functions may NOT access the local variables of other functions. Example (abbreviated): <script type="text/javascript"> /* <![CDATA[ */

39 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 function doStuff() { var george = "Wow"; alert(george); } function doSomethingElse() { var fred = "How about that!"; alert(fred); } /*]]>*/ </script>

In the above example, the variable george is a local variable of doStuff(), while the variable fred is a local variable of doSomethingElse(). Because fred and george are local variables in different functions, I can not access fred from doStuff(), nor can I access george from doSomethingElse(); either of these actions would result in a JavaScript error. Example (INCORRECT): <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = "Wow"; alert(fred); } function doSomethingElse() { var fred = "How about that!"; alert(george); } /*]]>*/ </script>

In the above INCORRECT example, I am trying to access george from doSomethingElse() and fred from doStuff(), neither of which are possible actions. Example (POSSIBLE): <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { var george = "Wow"; var fred = "How about that!"; alert(george); alert(fred); } /* <![CDATA[ */ </script>

In the above example, george and fred are both local variables of the SAME function; any process within that function, then, could access either george and/or fred. 40 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

We'll talk more about handling local variables in the next sections.

One Final Note Each function may contain local variables which have the SAME names as local variables contained in other functions. For instance, the following code is perfectly CORRECT: function doStuff() { var myNumber = 1; alert(myNumber); } function doSomethingElse() { var myNumber = 10; alert(myNumber); }

Because local variables are temporary, only existing for the duration of a given function, other functions may use the SAME local variable names. The technical reason for this is called PROTECTED NAMESPACE, which we don't need to go into here. Suffice it to say, that each function is like a separate universe, with its own collection of local variables, and that these local variables are separated or protected from the local variables in other functions. So, even though I am referring to the local variable myNumber in BOTH doStuff() and doSomethingElse(), these two variables, because they are both LOCAL variables, have NO relationship to one another whatsoever.

41 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Local and Global Variable Naming Conventions Officially, it doesn't matter what you name local and global variables, as long as you follow the naming conventions that we have discussed in earlier modules. In practice, however, there are standardized local and global variable naming conventions that many programmers follow. Here is the naming convention that I follow: Local variable names always begin with the prefix "my". Example: myText myCounter myPosition myNumber

Global variable names always begin with the prefix "the". Example: theText theCounter thePosition theNumber

Following a local/global naming convention, like the one outlined above, can really help you keep your local and global variables straight when you start writing more complex code. Trust me, it makes a difference! I also strongly recommend making your variable names reflect their purpose; this will make your code read much more like regular English than like techno-gibberish. For instance, if your variable is holding the result of a calculation, name it myResult or myAnswer rather than goobah or fred. Which of the following code examples is easier to read? var goobah = 1 + 1; var myAnswer = 1 + 1;

If I were dealing with temporary information, I might call my variable temp or myTemp. If I were dealing with some HTML text, I might call my variable myHTMLText or myText or theText (depending on whether it were local or global). In the same way, if I were writing a function which switched images, I would name that function using verb syntax, reflecting its purpose: switchImage() or handleImageSwitch(), rather than grumble() or snuffBox(). I had one student who named all of her functions after days of the week, and all of her variables after friends. Needless to say, she couldn't remember which function did what, or what the variables were for. Another person had the bright idea of naming a utility function

42 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

"fillUpMyCokePlease()". Again, no one can ever remember exactly WHAT that function is supposed to do! You get the idea. Do yourself a favor: name variables and functions after their purpose, not after your dog or to commemorate the purchase of your new lava lamp. You'll thank yourself later, trust me...

43 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Functions: Declaring Arguments You have already passed arguments to a built-in JavaScript method, the alert() method of the window instance of the Window object. Example: alert("Howdy");

Example (conservative syntax): window.alert("Howdy");

As mentioned earlier, methods are functions which are attached to objects. Functions, then, can receive arguments. Now that you know how to code a function, I can show you how to declare arguments for your functions. Example: <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { alert("Howdy"); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff('Boo');">Calling doStuff()</a></p> </body> </html>

In the above example, I have declared one function, doStuff(). In the BODY of my page, I have called doStuff() from the onClick event handler in the hyper-reference; I am passing doStuff one argument, the string "Boo". Now, how would I access that argument inside of the doStuff() function, and how could I pass the argument's data to the alert() method call in doStuff()? The easiest way to access an argument inside a function (and the only one we're going to explore in this introductory lecture) is to declare a local variable which will hold the argument data; this local variable MUST be declared within the parentheses characters following the name of the function, doStuff, in the function declaration. Note: You would NOT use the keyword, var, when declaring this type of local "argument" variable.

44 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example (abbreviated): function doStuff(fred) { // some code here... }

By declaring the local variable, fred, within the parentheses of the function declaration in the manner shown above, I am creating a container to hold the argument value being passed into the function. Within the function, then, I could access the local variable, fred, normally. Whatever argument has been passed to this doStuff function would be accessed via fred. Example (abbreviated): function doStuff(fred) { alert(fred); }

Now, in the above example, what value does fred actually contain, and what string would display in the alert dialog box? The answer is, it depends on what value has been passed as an argument to the doStuff function. Example: <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff(fred) { alert(fred); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff('Boo');">Calling doStuff()</a></p> <p><a href="#" onClick="doStuff('Ouch');">Calling doStuff() Again</a></p> </body> </html> Here is the above example displayed.

When the first link calls the doStuff function from its onClick event handler, it passes one argument to doStuff(), the string "Boo". That string value is passed into the local variable, fred, because fred has been declared as a local "argument" variable within the parentheses of the doStuff function declaration. The variable fred now contains the string value "Boo", which is passed to the alert() method in the above code; the alert() method then causes an alert dialog box to pop up which says "Boo".

45 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

The second link performs the same actions, only passing the string "Ouch" instead of "Boo". As you can see, both hyper-references call the SAME function, but each hyper-reference passes that function a different argument value. The function itself always performs the same tasks, but its behavior is altered slightly depending on the value of the argument passed into the local variable, fred. This is the seed of how you create generalized functions to perform variations on the same task! Without these sorts of local argument variables, a function would be forced to behave identically EVERY time you called it, just like the functions you saw in the previous sections. WITH these local "argument" variables, a function becomes much more flexible in the tasks it can perform. Just as I can pass more than one argument to a method/function, I can create more than one local "argument" variable by declaring those variables within the parentheses of the function declaration. Each of the local variable names declared between the parentheses of the function declaration would be separated by a comma. Example (abbreviated): function doStuff(fred, george) { alert(fred); alert(george); }

Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff(fred, george) { alert(fred); alert(george); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff('Boo', 'Scared You!');">Calling doStuff()</a></p> <p><a href="#" onClick="doStuff('Ouch', 'That Hurt!');">Calling doStuff() Again</a></p> </body> </html>

Here is the above example displayed.

46 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Arguments are always passed into the local "argument" variables for a function in sequence from left to right. The first argument passed to the above function would be passed into the first local argument variable, fred, and the second argument passed to the above function would be passed into the second local argument variable, george. The local "argument" variable name is irrelevant to which argument gets passed into which variable; the arguments are always passed into the function in order, left to right. Being able to declare local variables to hold arguments for a function is an extremely powerful tool. Obviously, we haven't time to explore all of the ramifications of this capability, but I'll try to show you something simple but practical to do with this power in the next section.

47 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Opening a New Window In this section, I'm going to write a function which throws up an alert dialog box, then opens a new browser window. To do this, I am going to call two methods of the window instance of the Window object: alert() (which you already know) and open() (which opens a new browser window). A call to the open() method is usually written out like this: window.open();

Even though the reference to the window object is understood implicitly, the conservative syntax given above looks much more like regular English, and is always used. The open() method requires three arguments, all strings. The first argument is the URL (absolute or relative) that will appear in the new window. The second argument is the NAME of the new window (which will NOT be visible to the user, but rather identifies the window in JavaScript). The third argument is a series of parameters, describing the appearance of the new window; this third argument may NOT contain any spaces, nor will it contain any additional quotation marks. Here is an example call to the open() method: window.open("http://www.yahoo.com/", "marian", "width=500,height=400"); Here is a link which demonstrates this code in action. Note: you MUST close this new window when you have finished looking at it; don't just hide it behind the current browser window, or some of my later code examples will not operate correctly. Notice how the new window in the above example had NO status bar, NO location bar, possibly even NO menubar or scrollbars; it wasn't resizable, either. The window was 500 pixels wide and 400 pixels high, and nothing else, because that was all I defined in the third argument of the open() method. To get a new browser window with more features, I have to state ALL of the features that I want, explicitly, in the third argument. Again, each of these features MUST be separated with a comma within the third argument string, and there must be NO SPACES anywhere or it won't work; this is NOT HTML, it just resembles it, so beware. A complete list of all of the window features available with the window.open() method is printed in "JavaScript: The Definitive Guide". Because these features are not pertinent to my demonstration, I am not going to go into all of them here. Here is a full-featured window called from JavaScript: window.open("http://www.yahoo.com/", "marian", "top=100,left=300,width=500,height=400,resizable,scrollbars,menubar,status,location,toolbar"); Here is a link which demonstrates this code in action. Notice that the left upper corner of the 48 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

new window is 100 pixels from the top and 300 pixels from the left. Note: again, you MUST close this new window when you have finished looking at it; don't just hide it behind the current browser window, or some of my later code examples will not operate correctly. Note also that the following will cause a SYNTAX ERROR because you may not separate the string between the last set of quotes, with a carriage return. window.open("http://www.yahoo.com/", "marian", "top=100,left=300,width=500,height=400,resizable,scrollbars, menubar,status,location,toolbar"); Now that I've talked about the window.open() method, let's add that method to our function declaration. Example: function doStuff() { alert("Here is Yahoo!"); window.open("http://www.yahoo.com", "marian", "width=500,height=400"); }

Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff() { alert("Here is Yahoo!"); window.open("http://www.yahoo.com", "marian", "width=500,height=400"); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick="doStuff();">Calling doStuff()</a></p> </body> </html>

Here is the above example displayed. Again, PLEASE CLOSE THE NEW WINDOW when you have finished with it! Obviously, if we hard-coded everything into our functions, we would have to write a different function for each message in the alert dialog box and each URL in the new window. This is an example of someplace where you would want to create a GENERALIZED function by

49 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

declaring ARGUMENTS for the function (as we discussed previously). Example: function doStuff(myMSG, myURL) { alert(myMSG); window.open(myURL, "marian", "width=500,height=400"); }

By creating a generalized function as I have in the example above, I can now simply pass arguments to doStuff, passing the string in myMSG to the alert() method, while passing the string in myURL to the window.open() method. Example (in context): <html> <head> <title>Sample JavaScript</title> <script type="text/javascript"> /* <![CDATA[ */ function doStuff(myMSG, myURL) { alert(myMSG); window.open(myURL, "marian", "width=500,height=400"); } /*]]>*/ </script> </head> <body> <p><a href="#" onClick= "doStuff('Here is Yahoo', 'http://www.yahoo.com/');">Yahoo Link</a></p> <p><a href="#" onClick= "doStuff('Here is Macromedia', 'http://www.macromedia.com/');"> Macromedia Link</a></p> </body> </html>

Here is the above example displayed. I can call this new generalized function from as many places as I wish. Again, there is NO correlation between what sort of information I pass into an argument variable, and the name of that variable; arguments are always passed into a function from left to right, the first argument going into the first variable, the second argument going into the second variable, etc. The order of the arguments being passed into a function, then, is critical. Variable names are also important, but mostly to help you, as the programmer, understand what the code is doing. To prevent confusion, the names of the local argument variables should be utilitarian, simple, and clear, which will make your code more comprehensible, as well as easier to read.

50 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Common Event Handlers Because of an incompatibility issue with Insight, click here for the next chapter about Common Event Handlers.

51 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Operators There are operators, and there are operands. Example: 1 + 1

The plus (+) sign is an OPERATOR, because it performs some action. The 1's are OPERANDS, because they are the things being acted, or operated, upon. You already know several JavaScript operators: + (plus) - (minus) * (multiply) / (divide) Here are some more operators, called COMPARISON operators, which you are probably also familiar with: < (less than) > (greater than) <= (less than or equal to) >= (greater than or equal to) You have already encountered the "gets" (=) operator, also called the "assignment" operator. As you know, this operator is NOT used for comparisons; rather, it takes whatever is on its right side, and places that information into whatever is on its left side. Example: var george = 1;

To make comparisons for equality, you need to use the EQUALITY operator, which is represented by two equals signs together: == (is equal to) If you want to test whether something is NOT equal, you would use the INEQUALITY operator, which is represented by an exclamation point and an equals sign together: != (is not equal to) Example: if (theSky == "gray") putOnYourOvercoat();

52 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

If the sky is gray, put on your overcoat. Example: if (theWater != "warm") turnOnTheHotWater();

If the water is not warm, turn on the hot water. Both of the above JavaScript examples use something called BRANCH logic; we'll talk more about JavaScript logic in the next section. I would also like to point out that I have created variable and function names which reflect PURPOSE, and, when used, sound very much like an English sentence; you should strive for this sort of clarity when writing JavaScript code. Here are some more operators: Logical AND: && (and) Logical OR: || (or) Example: if (theSky == "blue" && theTemperature >= 65) takeOffCoatAndTakeWalkOutside();

If the sky is blue AND the temperature is greater than or equal to 65 degrees Fahrenheit, take off coat and take walk outside. The condition above will only be met if BOTH the sky is blue AND the temperature is greater than or equal to 65; otherwise, nothing will happen. Example: if (theSky == "gray" || theRain == "falling") stayHomeWithABook();

If the sky is gray OR the rain is falling, stay home with a book. The condition above will be met if EITHER the sky is gray OR the rain is falling, which allows you more potential opportunities to stay home with a good book. Again, I'll discuss JavaScript branch logic syntax in more detail in the next section. JavaScript also provides something called the INCREMENT and DECREMENT operators, which either add or subtract 1 from something. ++ (increment) -- (decrement) Example: var myCounter = 0;

53 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 myCounter++; // myCounter is now equal to 1. myCounter--; // myCounter is now equal to 0. myCounter--; // myCounter is now equal to -1.

Without the increment and decrement operators, we would be forced to say: var myCounter = 0; myCounter = myCounter + 1; // myCounter is now equal to 1. myCounter = myCounter - 1; // myCounter is now equal to 0. myCounter = myCounter - 1; // myCounter is now equal to -1.

The increment and decrement counters provide a shorthand for adding 1 to a variable or subtracting 1 from a variable. This is extremely useful when counting mechanical repetitions using LOOP logic, another form of JavaScript logic which we will introduce in the next section. The last operator we will discuss is called the "assignment with addition" operator, or the "add by value" operator. += (add by value) This is another shorthand operator, like the increment/decrement operators. If we say "a += b", it is the same as saying "a = a + b". With the "by value" or "assignment with operation" operators, you get two actions for the price of one! The first operation is performed between the two operands, then the result of that operation is put into the first operand, leaving the second (right-hand) operand unchanged. Example: var fred = 1; var ethel = 2; fred += ethel;

In the above example, the variable fred starts out equal to 1, and the variable ethel starts out equal to 2. After the "add by value" operator works on the two variables, fred is now equal to 3, while ethel is still equal to 2. Again, this is because: fred += ethel;

is the same as saying: fred = fred + ethel;

This operator is VERY important in JavaScript because it is used to CONCATENATE, or join, strings together. You'll need to do this in order to create HTML text on-the-fly using JavaScript. 54 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example: var myName = "Michael"; var myText = "<p>Hi there, "; myText += myName; myText += "! How nice to see you!</p>";

In the above example, I am using the "add by value" operator to concatenate my HTML string together, adding in the user name stored in the variable myName, to create one whole paragraph of HTML code. If this were a real piece of JavaScript code, I would probably have gotten the user's name from a prompt or out of a form text INPUT field, and stored that information, placing it into HTML pages (using SCRIPT tags and the document.write() method) at key points to personalize the site for the user. There are a lot of other operators, but these are most (though not all) of the essential ones. For more information about operators, see "JavaScript: The Definitive Guide", Chapter 5.

Summary of Operators + (plus) - (minus) * (multiply) / (divide) = (gets, assignment) == (equality, is equal to) != (inequality, is not equal to) < (less than) > (greater than) <= (less than or equal to) >= (greater than or equal to) && (and, logical AND) || (or, logical OR) ++ (increment, adds 1 to operand) -- (decrement, subtracts 1 from operand) += (assignment with addition, add by value)

55 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Logic: A Simplified Overview Computer logic is an entire topic unto itself, which is really beyond the scope of this class. However, I wanted, at least, to INTRODUCE some of the concepts regarding computer logic to you before we went any further. Computer logic is not like human logic, it's really more of a routing process, or a mechanization process. In fact, it is comprised of only TWO forms in JavaScript: BRANCH logic, and LOOP logic.

Branch Logic Branch logic allows for simple decisions to be made, based on a CONDITION. A condition can be anything, and is TESTED, returning a value of either true or false (a boolean!). For example, let's say the CONDITION that I am testing is the color of the sky. Depending on what color the sky is, I am going to take off my hat, or put on my overcoat, or take out my umbrella. IF the sky is blue, then I am going to take off my hat. IF the sky is gray, then I am putting on my overcoat. IF the sky is dark gray OR black, then I am taking out my umbrella. I am about to go out of the house, and have come to a decision point. Depending upon the color of the sky, I am going to take different actions. My path, at this point, will BRANCH, depending upon the condition that I am testing (in this case, the color of the sky). This is an example of branching logic: I come to a decision point, and my path may BRANCH in any number of different ways, depending upon the result of the condition test that I am making. In JavaScript, this sort of logic is expressed using an IF STATEMENT. Example: if (theSky == "blue") takeOffMyHat();

First, I state the keyword, if, which makes this an IF STATEMENT, followed by a space. Then I put opening and closing parentheses characters; these parentheses characters are NOT, in this case, a function call operator, but a container for the CONDITION that I am testing. If whatever is being tested inside the parentheses is true, then I will perform whatever action follows the parentheses; if whatever is being tested inside the parentheses is false, then I will go on to the next line of JavaScript code, ignoring the statement following the parentheses. I may perform MULTIPLE lines of code if my condition is true by using curly-brace characters to define space, much as I do with the function declaration. Example: if (theSky == "blue") {

56 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 takeOffMyHat(); openTheWindowCurtains(); waveToTheNeighbors(); };

Unlike a function declaration, it is customary to place a semi-colon end-of-line marker at the end of the curly-braces of an if statement. If I want to BRANCH my decision point, I can use the ELSE statement in combination with the IF statement. Example: if (theSky == "blue") { takeOffMyHat(); } else { putOnMyGaloshes(); };

The else statement provides a "catch-all" action for anything which does not meet the first condition. Notice how I have NOT placed a semi-colon after the first set of curly-braces and BEFORE the else; you may ONLY place semi-colons AFTER the final curly-brace of the branch, and at the ends of lines of command BETWEEN the curly-braces. If I want to branch in more than two directions, I can use ELSE IF statements after my initial IF statement. Example: if (theSky == "blue") { takeOffMyHat(); } else if (theSky == "gray") { putOnMyOvercoat(); } else if (theSky == "black") { putOnMyOvercoat(); getOutMyUmbrella(); };

Note: I may include a final ELSE statement at the end of my branch if I want a catch-all statement for everything that doesn't meet the previous conditions. With sequential if/else-if statements in a set, as soon as one of the conditions is met in the branch, that part of the code is executed and the branch is ended. You can't get TWO separate portions of the branch to execute if TWO of the conditions are true; to do that, you need to use TWO separate IF statements rather than an if/else-if branch like the one above. That's enough about branch logic for this introductory lecture. There are other forms of branch logic, very similar to the if statement, which we do not have the time to cover in this class.

57 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Logic: A Simplified Overview, Part Two Loop Logic Computers are great at repeating things over and over again; it's one of the things that they do best. The computer's ability to repeat things precisely, again and again, has been classified in imperative programming languages as LOOP LOGIC. There are really only three kinds of loops, with many, many variations. Loop Type 1: Repeat an action WHILE, or for as long as, a condition is true. Loop Type 2: Repeat an action FOR a particular length of time, or FOR a given number of repetitions. Loop Type 3: Repeat an action until something occurs to stop it. Explanations Loop Type 1: Repeat an action WHILE, or for as long as, a condition is true. For example, I could be testing to see whether a bowl of rice has rice in it. If the bowl of rice has rice in it, then I would eat a grain of rice. As long as the bowl still had rice in it, I would continue to eat a grain of rice each time the loop was executed. Once the bowl was found to be empty, the condition would become false and the loop would end. Example: while (theGrainsOfRiceInTheBowl > 0) { eatAGrainOfRice(); }

Loop Type 2: Repeat an action for a particular length of time, or for a given number of repetitions. For example, I might wish to sort 3 shrimp into a basket. I could create a loop, called a FOR loop, which would allow me to perform my action three times, then stop. Each time through the loop, I would sort one shrimp into the basket. A local counter variable would be in place, which would be INCREMENTED (have 1 added to it) each time through the loop. When the counter reached 3, the loop would end. Example: for (myCounter = 0; myCounter < 3; myCounter++) { sortShrimpIntoBasket(); }

In FOR loops, like the above example, the condition statement has three parts, which can be defined as (initialize; test; increment/decrement). Let's look at this portion of the FOR loop in

58 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

greater detail. The first part, initialize, declares and initializes a local counter variable which may possess any name; in this example, the counter has been initialized to 0. Note: the local variable being declared here does NOT require the var keyword. The second part, test, evaluates whatever condition is placed there. In this example, I am testing the counter and seeing whether it is less than 3. If the counter is less than three, the condition is true and the statements between the curly-braces are executed. If the counter is greater than or equal to 3, than the condition is false and the loop ends without executing any further code. The third part, increment/decrement, is executed after the lines of code between the curlybraces have been executed. In this example, I am incrementing (or adding 1 to) my counter variable. Each time through the loop, then, the counter increases in number until it reaches 3; at that point, the condition check in the center becomes false and the loop ends, preventing further incrementation. In my live classes, I would act out the part of the computer running the loop. Obviously, that is not practical here. As an exercise, however, I am going to write out the iterations of the loop. myCounter is declared and initialized to 0. Is myCounter less than 3? Yes, so the loop executes, and sorts a shrimp into the basket. The third part of the structure is executed, incrementing the myCounter variable by 1. myCounter, then, is now equal to 1. Is myCounter less than 3? Yes, it is, so the loop executes, and sorts a shrimp into the basket. The myCounter variable is incremented again, and is now equal to 2. Is myCounter less than 3? Yes, it is, so the loop executes yet again, and sorts a shrimp into the basket. The myCounter variable is incremented again, and is now equal to 3. Is myCounter less than 3? No, myCounter is equal to 3, so the condition is false, and the loop ends. You would be amazed at the powerful things you can accomplish with this sort of mind-numbing repetition. The FOR loop is essential to code of any sophistication or ability. Loop Type 3: Repeat an action until something occurs to stop it. In my live classes, I act out the part of a computer-generated stopwatch, which keeps ticking away the seconds until someone presses a pretend button on my hand. You get the idea. This sort of "recursive" loop is usually created in JavaScript using the setTimeout() method of the Window object, which recursively calls its own function over and over again. A demonstration of code for this sort of loop is outside the scope of this class. One thing you may have noticed about loops is that, regardless of the type of loop under

59 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

consideration, a loop performs ONE action or one SET of actions at a time; these actions are repeated 1) WHILE a condition is in place, 2) FOR a given number of repetitions, or 3) until something occurs to stop the loop. We have barely scratched the surface of loop logic; there are a tremendous number of variations on the loop statements I've mentioned here. Loops are central to performing a wide variety of activities in JavaScript (as well as every other imperative programming language around). You might use loops to generate HTML code (creating repetitive structures like table rows, for instance), or for calculations of one sort or another, or to create game logic, or to access information from complex objects or arrays, or for any one of a vast number of other purposes. As I mentioned earlier, the use of logic, especially loop logic, is an entire world unto itself which is entirely beyond the scope of this introductory lecture.

60 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

The window.open() Method Revisited The window.open() method RETURNS a reference to the new browser window ITSELF. If you store this REFERENCE to the new browser window in a variable, you can then manipulate the actual new browser window in many ways, via appropriate methods. Let's look at ONE of these methods, focus(). The focus() method of the Window object allows us to bring a browser window into FOCUS; that is to say, it allows us to SELECT the browser window without physically touching it, bringing that browser window in front of everything else. When you call the window.open() method, you must place the returned window reference into a variable, either global or local. Here's an example of what I mean. Example: function doStuff() { var myWindow = window.open("http://www.yahoo.com/", "marian", "width=300,height=200"); }

Once you have the reference to the new window in a variable, you can access methods of that particular window via the variable name. For instance, after the window has been opened, we will FOCUS the window by calling the focus() method of the window instance of the Window object, using dot-syntax to do so. Example: function doStuff() { var myWindow = window.open("http://www.yahoo.com/", "marian", "width=300,height=200"); myWindow.focus(); }

Using dot-syntax, I have called the focus() method of the variable, myWindow, which contains the reference to "marian", the new browser window; by doing so, I can bring "marian" forward. This can be important if the window "marian" has already been brought into existence, and has been deselected without closing it. If a window has been deselected without being closed, it gets blurred and sent behind the main browser window; when a method, like doStuff() above, opens "marian" again, the new URL and appearance information is applied to the existing "marian" window, but most web browsers will NOT focus "marian", bringing her forward, unless the focus() method has been applied to her. Of course, the most EXCITING thing about having a direct JavaScript reference to a browser window is that you can then send HTML, CSS, JavaScript, or other information into that new browser window, creating many dynamic possibilities (all of which, sadly, are beyond the scope of this class).

61 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Due to security restrictions in JavaScript, the CURRENT browser window can NOT be manipulated in the same way that a NEW browser window (created by the window.open() method) can. This restriction is in place to prevent JavaScript programmers from messing with a user's browser window without their permission, a very reasonable precaution. As I have mentioned, however, a NEW browser window, one which YOU have created, is not subject to these restrictions, and can be moved around, changed in dimension, brought forward and back, and many other things, all using built-in JavaScript methods accessed via a window reference in a variable, like the one in the example above. Although I have not created an exercise for this section, I strongly urge you to experiment with some of these methods, to get comfortable with accessing your window via a variable containing the window's object reference. Remember that you may place that reference within either a local OR a global variable. I hope that I have whetted your appetite a little bit. Next, we're going to look at custom status bar messages; these also require the manipulation and passing of returned values, although in a considerably different manner.

62 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

The return Keyword A JavaScript function, when executed, may send some piece of data back to whatever process originally called it using the return keyword. For instance, I might make a calculation function which takes in numbers as arguments, performs a complex calculation (a mortgage payment calculation would be an appropriate example), and spits out an answer. The alert() method that you have used so far to spit out answers is obviously inadequate to real work; the return keyword is what you will need to use to get information out of a function. Built-in JavaScript methods use the return keyword to spit out many different types of values, which you will need to intercept and process for one reason or another, placing those returned values into local or global variables so that you can use and manipulate that information. In addition, you will be called upon to return values yourself, not only between functions, but also to the web browser. And it's not only numbers, strings, or booleans which can be returned from a function or method; references to objects can ALSO be returned from a function, such as a reference to a new browser window. I'll talk more about many of these subjects later on. Let's look at the addMe() function. Example: function addMe(myFirstNum, mySecondNum) { var myAnswer = myFirstNum + mySecondNum; alert(myAnswer); }

The above example function DOES spit out an answer, but it does so via the medium of an alert dialog box. A function like this would NOT spit out information in an alert dialog box, it would normally be called by another function, which would need to receive the calculation result; this requires the use of the return keyword. Example (abbreviated): function addMe(myFirstNum, mySecondNum) { var myAnswer = myFirstNum + mySecondNum; return myAnswer; }

Example (in context): function doStuff() { var myNumberOfCats = 4; var myNumberOfDogs = 2; var myTotalNumberOfPets = addMe(myNumberOfCats, myNumberOfDogs); alert(myTotalNumberOfPets); } function addMe(myFirstNum, mySecondNum) {

63 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115 var myAnswer = myFirstNum + mySecondNum; return myAnswer;

}

In the above example, I have called the addMe() function from inside doStuff(); this call passes myNumberOfCats and myNumberOfDogs as arguments to the addMe() function, which adds these values together (using its local variables, myFirstNum and mySecondNum). Once this calculation has been finished, the variable containing the result (myAnswer) is placed after the return keyword, which sends that information back to the calling function, doStuff(). In effect, the addMe() function call in doStuff() is replaced with whatever value is returned from the addMe() function; in this case, the number 6. That answer, 6, is put into the local variable, myTotalNumberOfPets, by the "gets" operator, whereupon that answer is displayed; for simplicity's sake, I have used the alert() method to display the answer, but a real function would probably be doing something much more involved with the information. This is an over-simplified demonstration of the return keyword. Obviously, you would never need to go through this much trouble just to add two numbers together. I am trying to show you the mechanics of this process using code that is extremely easy to analyze. Note: The return keyword MUST be part of the LAST statement in a function, because once the return keyword has sent its value back to the calling function, the function containing the return keyword ENDS, regardless of whether there is any more code following that keyword or not. Example: function addMe(myFirstNum, mySecondNum) { var myAnswer = myFirstNum + mySecondNum; return myAnswer; alert(myAnswer); }

In the above example, the call to the alert() method would NOT be executed because it follows the statement containing the return keyword. Again, after the return keyword statement has been executed, any lines of code following that statement are ignored. Many functions and methods in JavaScript return values of one sort or another to a calling process or function. In the remainder of this module, I will be showing you two different uses of return values which merely scratch the surface (once again) of the vast number of things you can do with this functionality.

64 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Form Pulldown Menus Used as Navigation Elements In this section, I am going to talk about "submitting" a FORM to a JavaScript function, then extracting information from that form using dot syntax and a number of specialized keywords. To demonstrate this process, we are going to look at a FORM pulldown menu used as a navigational element. Here is an example of what I mean. In an earlier module, we discussed creating form pulldown menus, and using the VALUE attribute of the individual OPTION tags to store URL information. Example (abbreviated): <option value="http://www.yahoo.com/">Yahoo</option>

For the purposes of this demonstration, I am going to name my SELECT tag "destList"; I do NOT need to name my FORM tag. Example: <form> <select name="destList"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http:/fog.ccsf.org/~srubin">Steve Rubin</option> </select> </form> When you "submit" your form to a JavaScript function, you will NOT use the submit INPUT; instead, you will use the generic button INPUT. You will pass the value, this.form, as the argument to your function, which will, essentially, pass a complete copy of the form to the function. Note: the this keyword, and the value, this.form below. It turns out that, in this particular case, the this keyword refers to the button, and the form property of the button is really a special keyword referring to the entire form attached to the button. The phrase this.form, then, can be passed as an argument to a function; the reference encompasses the entire form enclosed by the FORM tag attached to the given form element. The following example presumes that the function I'm about to create is called goToNewPage().

65 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example (abbreviated): <input type="button" value="Go" onclick="goToNewPage(this.form);"> Example (in context): <form> <select name="destList"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> <input type="button" value="Go" onclick="goToNewPage(this.form);"> </form> Now, I'm ready to create my function; the function will have one local argument variable, myForm, which will contain the reference to the form (passed using this.form as an argument from the event handler). Example: function goToNewPage(myForm) { // lines of code here... } In this function, I'm going to need to look at the destList SELECT tag within the form; this can be done using dot syntax. Example: myForm.destList Now, I'm going to need to look at the options[] array within the destList SELECT tag. All of the OPTION tags in a SELECT tag are stored in an options[] array. This, too, will be accessed using dot syntax. Example: myForm.destList.options[] What I really need to see, however, is the value property of the desired option in the options[] array. The value property of the option contains the URL string that we've placed in the VALUE attribute. 66 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example: myForm.destList.options[].value The problem with this syntax is that we do not know WHICH option we want! In the options[] array, as you might expect, the FIRST option (in this case, the option for Yahoo) is stored in options[0], the SECOND option (the option for the W3C) is stored in options[1], etc. If I want to get the URL value for Mozilla, then, I would need to look at options[2] in this example. Example: myForm.destList.options[2].value The above example will return the string value, "http://www.mozilla.org/". Alright, this hard-coding is good enough, in its way, but HOW do I find out WHICH option the USER has selected? There is a special keyword of the SELECT tag, selectedIndex, which returns the number of the option which the user has selected. Example: myForm.destList.selectedIndex I need to put the above code INTO the array access operator ([]) for the options[] array to access the selected option. Example: myForm.destList.options[myForm.destList.selectedIndex].value I would then place this extracted information into some sort of local variable. Example: var mydest = myForm.destList.options[myForm.destList.selectedIndex].value; Once I have extracted the URL string value that I require, I will need to ASSIGN that value to the browser window's location object. The location property of the window instance of the Window object gives us access to the location bar, and will advance the page in the web browser when assigned to the desired URL. 67 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Example: window.location = "http://www.mozilla.org/"; Example: var mydest = myForm.destList.options[myForm.destList.selectedIndex].value; window.location = mydest; Example (complete function): function goToNewPage(myForm) { var mydest = myForm.destList.options[myForm.destList.selectedIndex].value; window.location = mydest; } In the example cited earlier, there was also a pulldown menu which changed the page location WITHOUT hitting a "Go" button. This functionality was achieved using the onchange event handler, which is triggered when the state of a form element is changed by the user; the onchange event handler would be added to the SELECT tag for the pulldown menu. Example: <select name="destList" onchange="goToNewPage(this.form);"> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> <option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> In the above example, the Yahoo option is pre-selected. If the user wishes to go to Yahoo, then, they will NOT be able to do so, because the onchange event handler is ONLY called when the state of the pulldown menu is CHANGED. To get around this problem, web programmers add some sort of blank option to the pulldown menu; this blank option usually tells the user what they ought to do with the pulldown menu. Example: <select name="destList" onchange="goToNewPage(this.form);"> <option>Choose dest:</option> <option value="http://www.yahoo.com/">Yahoo</option> <option value="http://www.w3.org/">W3C</option> <option value="http://www.mozilla.org/">Mozilla</option> 68 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

<option value="http://fog.ccsf.org/~srubin">Steve Rubin</option> </select> That's it! Here's the example page again. I strongly urge you to try typing out this code for yourself, by hand, to get a feel for the process.

69 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Simple Debugging Techniques for JavaScript You are going to run frequently into JavaScript code that doesn't work. In fact, MOST code fails to operate correctly the first time you test it, for one reason or another. It is outside the scope of this introductory lesson to go into very much detail regarding debugging techniques. Here is a list of some of the most common errors that students make: Spelling: JavaScript is CASE-SENSITIVE. Check your spellings! Incorrectly-placed Carriage Returns: Students often place carriage returns in the middle of parentheses for methods or functions, which usually doesn't work. Spaces: Names may have NO SPACES in them. Some arguments may also not have spaces in them, depending on the method in question. Don't forget to follow the naming conventions that I outlined in the earlier modules! Missing Quote Marks: One quote mark missing, and your JavaScript program will fail. The same holds true for missing parentheses or curly-braces, etc. I get caught by this myself surprisingly often. There is one easy technique that you can use to debug code when something doesn't work: add a call to the alert() method into a sequence of lines of code. Test your code, and see if the alert dialog box you inserted shows up or not. Remove that alert(), and put another one someplace else. Keep testing with the alert() method in various locations until you pinpoint the precise point in the code where everything breaks down. Debugging code is almost an art form, and requires a good deal of experience. The few techniques I've outlined here, however, should help you to get started. The biggest secret to debugging code is NOT to let yourself get frustrated. Mistakes and bugs in code are NORMAL, and you should ALWAYS expect them. If code works right the first time, it's usually a fluke and a cause for celebration; I dance around the house, patting myself on the back, on the rare occasions when that happens! Methodical coding procedures are also of paramount importance. Once you've gotten a grasp of what good coding form is all about, you will need to develop certain habits, producing code in a very regular and regimented fashion. Again, I can't go into details here, but I've given you a lot of hints throughout this entire online course, both in HTML, in CSS, and in JavaScript, which can be applied to ANY coding that you do. I have found that debugging syntax errors is much easier in Firefox than IE. Click Tools, Error Console and then Errors to debug in Firefox. The error message and the line number are displayed. Depending on the error, the approximate position of the error is displayed. Firefox also has a good debugger add-on, called Firebug.

70 of 71

11/6/10 12:56 PM


name

http://insight.ccsf.edu/mod/book/print.php?id=136115

Some Final Thoughts about JavaScript We have only explored the simplest tasks in JavaScript; it is capable of doing so much more. With JavaScript, you can create Dynamic HTML pages, with animations, or contextual help menus, or special menu systems, or complete interactive applications built out of HTML elements. Flash and Director/Shockwave both use JavaScript as their native scripting language, opening the doorway to interactive animated games, and interfaces, and multimedia-rich experiences of every description. On the Web, JavaScript is the glue that ties all of the multimedia elements together, and allows you to make really interesting things out of basic pieces. I hope that you have found our JavaScript discussion interesting, and that it has whetted your appetite for more programming, or, at the very least, given you a little necessary information. Remember that programming itself is all about breaking big things down into the smallest, most manageable single tasks; always start with the non-controversial things, single tasks that you understand, and get those down FIRST. Once you've gotten the easy things down, you'll be surprised at how much more readily everything else falls into place! "Divide and Conquer" is the rule of law in programming; if you divide your problem into simple bits, you'll conquer the entire task! If you really want to learn JavaScript so that you can harness its interactive power, I strongly urge you to start coding projects of every description NOW. Flash, with its streaming sound and animation capabilities, is, by far, the most accessible environment for creating immediate, fun, "flashy" pieces using JavaScript programming that will provide you with a lot of immediate gratification. Dynamic HTML work, however, with its direct connectedness to HTML, is more at the heart of JavaScript's DOM and other built-in features. Whichever way you turn, JavaScript programming will give you a lot of satisfaction.

71 of 71

11/6/10 12:56 PM


Common Event Handlers

11/6/10 2:00 PM

Common Event Handlers JavaScript has a long list of event handlers which it understands. Some of the most commonly used event handlers are: onclick onmouseover onmouseout onchange onload Note: It used to be customary to capitalize interior letters of event handlers, e.g., onClick and onMouseOver. They still work but will not validate for XHTML.

In addition to these common ones, there are two less common but conceptually important event handlers I feel should also be mentioned: onfocus onblur

Again, event handlers would be added to an HTML tag, and would be triggered upon that event occuring to the tag. In order to support older browsers, most event handlers must be placed within clickable tags, such as A (anchor) and INPUT. onclick we've already discussed, so I won't repeat myself here. The onmouseover event occurs when a user passes their mouse over an element. Example: <a href="#" onmouseover="alert('Hi');">onmouseover Event</a>

Displayed: onmouseover Event The onMouseOut event occurs when a user passes their mouse AWAY from an element. Example: <a href="#" onmouseout="alert('Bye');">onmouseout Event</a>

Displayed: onmouseout Event The onmouseover and onMouseOut events are usually used to trigger image switches and custom status bar messages; we'll talk about custom status bar messages a little later in this module. http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 1 of 3


Common Event Handlers

11/6/10 2:00 PM

The onchange event handler is triggered when an element changes its state. The onchange event handler is most commonly used with form elements, such as the SELECT tag pulldown menu. Example: <form> <select name="testPulldown" onchange="alert('You changed me');"> <option value="1">First Choice</option> <option value="2">Second Choice</option> <option value="3">Third Choice</option> </select> </form>

Displayed: First Choice

This sort of JavaScript-enhanced interface element is most commonly used for navigational purposes on a web site; we'll talk about that, as well, a little later in this module. The onload event handler has to do with the loading of HTML pages into a browser window. When a page is completely loaded, when all of its graphics and text and sound files and movies are fully downloaded, the onLoad event is triggered. The onLoad event handler ALWAYS goes in the BODY tag of the HTML page. I am not going to demonstrate this one here; its true purpose is beyond the scope of this class. All I will say is that the onLoad event handler is most commonly used to trigger initialization functions for an HTML page. The onfocus and onblur event handlers are mostly connected with form elements, and are not commonly used. However, the concepts of FOCUS and BLUR are extremely important, so I thought I should mention them. When you SELECT something on the computer, you are giving that thing FOCUS. When you DESELECT something, you are giving it BLUR. Here is a text field:

When you click on the text field, you are giving it FOCUS. If there were an onfocus event handler in the text field, it would be triggered when you selected the text field. When you click AWAY from a selected text field (DESELECTING the element), you are giving that text field BLUR. If there were an onblur event handler in the text field, it would be triggered when you deselected that field. Note: DO NOT try the above onfocus/onblur examples using actual JavaScript code and alert dialog boxes, as this may cause browser crashing. Focus and blur events occur, not just with form elements, but with browser windows, frames, and, in short, http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 2 of 3


Common Event Handlers

11/6/10 2:00 PM

any element which can be selected or deselected. I mention the concept of focus and blur now because we will be dealing with focus methods later in this module, and I want to make certain that you understand what I mean when I say FOCUS. Again, there are a lot more event handlers. See "JavaScript: The Definitive Guide" for more information.

http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 3 of 3


Common Event Handlers

11/6/10 2:00 PM

Common Event Handlers JavaScript has a long list of event handlers which it understands. Some of the most commonly used event handlers are: onclick onmouseover onmouseout onchange onload Note: It used to be customary to capitalize interior letters of event handlers, e.g., onClick and onMouseOver. They still work but will not validate for XHTML.

In addition to these common ones, there are two less common but conceptually important event handlers I feel should also be mentioned: onfocus onblur

Again, event handlers would be added to an HTML tag, and would be triggered upon that event occuring to the tag. In order to support older browsers, most event handlers must be placed within clickable tags, such as A (anchor) and INPUT. onclick we've already discussed, so I won't repeat myself here. The onmouseover event occurs when a user passes their mouse over an element. Example: <a href="#" onmouseover="alert('Hi');">onmouseover Event</a>

Displayed: onmouseover Event The onMouseOut event occurs when a user passes their mouse AWAY from an element. Example: <a href="#" onmouseout="alert('Bye');">onmouseout Event</a>

Displayed: onmouseout Event The onmouseover and onMouseOut events are usually used to trigger image switches and custom status bar messages; we'll talk about custom status bar messages a little later in this module. http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 1 of 3


Common Event Handlers

11/6/10 2:00 PM

The onchange event handler is triggered when an element changes its state. The onchange event handler is most commonly used with form elements, such as the SELECT tag pulldown menu. Example: <form> <select name="testPulldown" onchange="alert('You changed me');"> <option value="1">First Choice</option> <option value="2">Second Choice</option> <option value="3">Third Choice</option> </select> </form>

Displayed: First Choice

This sort of JavaScript-enhanced interface element is most commonly used for navigational purposes on a web site; we'll talk about that, as well, a little later in this module. The onload event handler has to do with the loading of HTML pages into a browser window. When a page is completely loaded, when all of its graphics and text and sound files and movies are fully downloaded, the onLoad event is triggered. The onLoad event handler ALWAYS goes in the BODY tag of the HTML page. I am not going to demonstrate this one here; its true purpose is beyond the scope of this class. All I will say is that the onLoad event handler is most commonly used to trigger initialization functions for an HTML page. The onfocus and onblur event handlers are mostly connected with form elements, and are not commonly used. However, the concepts of FOCUS and BLUR are extremely important, so I thought I should mention them. When you SELECT something on the computer, you are giving that thing FOCUS. When you DESELECT something, you are giving it BLUR. Here is a text field:

When you click on the text field, you are giving it FOCUS. If there were an onfocus event handler in the text field, it would be triggered when you selected the text field. When you click AWAY from a selected text field (DESELECTING the element), you are giving that text field BLUR. If there were an onblur event handler in the text field, it would be triggered when you deselected that field. Note: DO NOT try the above onfocus/onblur examples using actual JavaScript code and alert dialog boxes, as this may cause browser crashing. Focus and blur events occur, not just with form elements, but with browser windows, frames, and, in short, http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 2 of 3


Common Event Handlers

11/6/10 2:00 PM

any element which can be selected or deselected. I mention the concept of focus and blur now because we will be dealing with focus methods later in this module, and I want to make certain that you understand what I mean when I say FOCUS. Again, there are a lot more event handlers. See "JavaScript: The Definitive Guide" for more information.

http://fog.ccsf.edu/%7Esrubin/evhand.html

Page 3 of 3


http://insight.ccsf.edu/mod/resource/view.php?inpopup=true&id=136121

12/1/10 2:11 PM

Reference in Musciano Book: Ch. 15

Introduction to XML What is XML? XML is an acronym for Extensible Markup Language and is an emerging format to structure, store and send information. XML allows the author to define their own tags and their own document structure. XML is not a replacement for HTML. In future web developments it is likely that XML will be used to describe and transfer data and HTML used to format and display the same data. XML can be seen as a cross-platform, independent tool for exchanging data. For further information see: W3C on XML.

XML and CSS: You can create a webpage by creating an XML document with your own tags that represent the content of the webpage, but not the format. To format the webpage, you can use a linked style sheet. An XML document has a filetype of .xml. EXAMPLE OF XML CODE: <discography> <title>Discography for Simply Red</title> <cd>Picture Book <track>Holdin Back the Tears</track> <track>Money's Too Tight to Mention</track> </cd> </discography> EXAMPLE OF RELATED CSS CODE: discography {background-color: #FFB6C1; width: 1000px; padding: 5px; position: absolute; left: 0px; top: 0px; margin-left: 0px;} title {display: block; font-size: 22pt; color: red; font-weight: bold; font-family: arial, helvetica, sans-serif; margin-top: 10pt; margin-left: 5pt; background-image: url(roseback.jpg); width: 400px; padding: 3px;} cd {display: block; font-size: 14pt; color: red; font-weight: bold; font-family: arial, helvetica, sans-serif; margin-top: 20pt; margin-left: 20pt;} track {display: list-item; font-size: 12pt; font-family: times new roman, times, serif; margin-left: 25pt;}

Skeletal XML Document: <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> <?xml-stylesheet type="text/css" href="sred.css" ?> <discography> . . </discography> Here is the complete XML document. View source. <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> This is the XML declaration and is always the first line in any XML document. It signals to the processor that the document is written using XML and provides information about how the code is to be interpreted by the parser. <?xml-stylesheet type="text/css" href="sred.css" ?> This is the statement that references the linked CSS file, which will format the webpage. Page 1 of 2


http://insight.ccsf.edu/mod/resource/view.php?inpopup=true&id=136121

12/1/10 2:11 PM

All elements in an XML document must be nested within a single root element . In our example, the following is the root element. <discography> . . </discography>

XML Tutorials: W3 Schools Tizag xmlfiles.com

XML Book: A good introductory book about XML is: New Perspectives on XML, Second Edition, Comprehensive Patrick Carey ISBN 13: 978-1-4188-6064-6 Š 2007 ISBN 10: 1-4188-6064-6 Publish date: August 17, 2006 For more information about XML, I suggest you take CNIT 131A.

You are logged in as Donald Siino (Logout)

CNIT132-META-FALL-2010 0.16452 secs RAM: 2.2MB RAM peak: 2.3MB Included 54 files ticks: 17 user: 13 sys: 1 cuser: 0 csys: 0 Load average: 1.52 Record cache hit/miss ratio : 0/0

Moodle Theme by NewSchool Learning

Page 2 of 2


GoSquared

CSS3 Help Sheet

Equally Rounded Corners

Text Shadow

Box Resize

-webkit-border-radius -moz-border-radius border-radius

Webkit

text-shadow

resize

Firefox Standard

Syntax

both vertical horizontal

5px 5px 5px #000000

min-height

Individually Rounded Corners

x-offset, y-offset, blur, color

min-width

Webkit

filter: dropshadow( )

overflow: auto

-webkit-border-top-left-radius -webkit-border-top-right-radius -webkit-border-bottom-left-radius -webkit-border-bottom-right-radius

Syntax

Firefox -moz-border-radius-topleft -moz-border-radius-topright -moz-border-radius-bottomleft -moz-border-radius-bottomright

Standard border-top-left-radius border-top-right-radius border-bottom-left-radius border-bottom-right-radius

(color=#000000, offx=5, offy=5) color, x-offset, y-offset

RGBA background-color: rgba(R, G, B, A) color: rgba(R, G, B, A)

-webkit-box-shadow -moz-box-shadow box-shadow

Syntax

Webkit Firefox Standard

Multiple Columns Webkit -webkit-column-count -webkit-column-gap

Firefox -moz-column-count -moz-column-gap

Standard column-count column-gap

Syntax

5px dashed #000000 thickness, style, color

Gradients -webkit-gradient

255, 255, 255, 1 Red, Green, Blue, Opacity (0-255, 0-255, 0-255, 0-1)

Syntax

Font Face font-family: ‘ ’; src: url(’ url_of_font_file‘); src: local(’ ‘), url(’ url_of_font.woff‘) format(’woff ‘), url(’url_of_font.ttf’) format(’truetype’); More info by Paul Irish: http://bit.ly/cC76RC

5px 5px 5px #000000 x-offset, y-offset, blur, color

outline

Syntax

@font-face

Box Shadow

Outline

Box Sizing box-sizing: content-box -moz-box-sizing: content-box -webkit-box-sizing: content-box -ms-box-sizing: content-box -o-box-sizing: content-box; -icab-box-sizing: content-box; -khtml-box-sizing: content-box;

Syntax content-box acts like a standard box-model element border-box padding and border render inside the box

Download this Help Sheet now at gosquared.com/liquidicity Put it on your wall

linear type of gradient left bottom right bottom left top right top position of start & end color-stop(0.5, rgb(R,G,B)) position & color of stops -moz-linear-gradient Syntax

left right top bottom position of start & end rgb(R, G, B) 50% position & color of stops

Selectors Incredibly powerful, but we couldn’t possibly fit them on this sheet. Info at 456 Berea Street: http://bit.ly/cKO24D CSS3 is not yet supported in all browsers. Graceful degradation in older browsers such as IE6 (arghh) is highly recommended.

© 2010 Go Squared Ltd.


GoSquared Syntax

CSS Help Sheet

Margins + Padding

Write styles for any element selector {property: value;}

height; width;

height

External Style Sheet <link rel=”stylesheet” type=”text/css” href=”style.css” />

width

margin-top; margin-right; margin-bottom; margin-left;

border

padding-top; padding-right; padding-bottom; padding-left;

Internal Style <style type=”text/css”> selector {property: value} </style>

Shorthand

margin

padding

background border border-bottom border-left border-right border-top font list-style margin padding

Inline Style

Border

Comments

<tag style=”property: value”>

border-width Width of the border border-style dashed; dotted; double; groove; inset; outset; ridge; solid; none;

/* Comments */

General class

String preceded by a full stop (.)

ID

String preceded by a hash (#)

div

Formats structure or block of text

span

Inline formatting

color

Foreground colour

cursor

Appearance of the cursor

display

block; inline; list-item; none

overflow

How to handle content that overflows its box. visible; hidden; scroll; auto visible; hidden

visibility

Font font-style

italic, normal

font-variant

normal, small-caps

font-weight

bold, normal, lighter, bolder, integer [100-900]

font-size

Size of the font

font-family

Specific font[s] to be used.

Text letter-spacing Space between letters line-height Vertical space between baselines text-align textdecoration text-indent

Horizontal alignment blink, line-through, none, overline, underline First line indentation

textcapitalise, lowercase, uppercase transform vertical-align Vertical alignment word-spacing Spacing between words

border-color

Colour of the border

Position clear

If any floating elements around the element both, left, right, none

float

Floats to a specified side left, right, none The left position of an element auto, length values [pt, in, cm, px]

left top

The top position of an element auto, length values [pt, in, cm, px]

position

static, relative, absolute

z-index

Above or below overlapping elements auto, integer [higher numbers on top]

all braille embossed handheld print projection screen speech tty tv

background-color Colour of background background-image Background image url(’’) background-repeat repeat, no-repeat, repeat-x, repeat-y backgroundBackground image scrolls with element attachment scroll, fixed background(x y), top, center, bottom, left, right position

list-styleposition list-styleimage

Units Length % em pt px Keywords

List list-styletype

:hover :active :focus :link :visited :first-line :first-letter

Media Types

Background

Type of bullet or numbering in the list disc; circle; square; decimal; lower-roman; upper-roman; lower-alpha; upper-alpha; none Position of the bullet or number in a list inside; outside

bolder lighter larger Developing for IE6 is a lost cause.

Image to be used as the bullet in the list

Download this Help Sheet now at gosquared.com/liquidicity Original by the awesome Leslie Frank: http://lesliefranke.com/2005/10/css-cheat-sheet/

Put it on your wall

Pseudo Selectors

© 2010 Go Squared Ltd.


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.