Friends

This is default featured post 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

This is default featured post 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.This theme is Bloggerized by Lasantha Bandara - Premiumbloggertemplates.com.

Rabu, 26 Oktober 2011

XML Tutorial

What is XML? XML (eXtensible Markup Language) is a meta-language; that is, it is a language in which other languages are created. In XML, data is "marked up" with tags, similar to HTML tags. In fact, the latest version of HTML, called XHTML, is an XML-based language, which means that XHTML follows the syntax rules of XML.
XML is used to store data or information. This data might be intended to be by read by people or by machines. It can be highly structured data such as data typically stored in databases or spreadsheets, or loosely structured data, such as data stored in letters or manuals.

XML Benefits

Initially XML received a lot of excitement, which has now died down some. This isn't because XML is not as useful, but rather because it doesn't provide the Wow! factor that other technologies, such as HTML do. When you write an HTML document, you see a nicely formatted page in a browser - instant gratification. When you write an XML document, you see an XML document - not so exciting. However, with a little more effort, you can make that XML document sing!
This section discusses some of the major benefits of XML.

XML Holds Data, Nothing More

XML does not really do much of anything. Rather, developers can create XML-based languages that store data in a structure way. Applications can then use this data to do any number of things.

XML Separates Structure from Formatting

One of the difficulties with HTML documents, word processor documents, spreadsheets, and other forms of documents is that they mix structure with formatting. This makes it difficult to manage content and design, because the two are intermingled.
As an example, in HTML, there is a <u> tag used for underlining text. Very often, it is used for emphasis, but it also might be used to mark a book title. It would be very difficult to write an application that searched through such a document for book titles.
In XML, the book titles could be placed in <book_title> tags and the emphasized text could be place in <em> tags. The XML document does not specify how the content of either tag should be displayed. Rather, the formatting is left up to an external stylesheet. Even though the book titles and emphasized text might appear the same, it would be relatively straight forward to write an application that finds all the book titles. It would simply look for text in <book_title> tags. It also becomes much easier to reformat a document; for example, to change all emphasized text to be italicized rather than underlined, but leave book titles underlined.

XML Promotes Data Sharing

Very often, applications that hold data in different structures must share data with one another. It can be very difficult for a developer to map the different data structures to each other. XML can serve as a go between. Each application's data structure is mapped to an agreed-upon XML structure. Then all the applications share data in this XML format. Each application only has to know two structures, its own and the XML structure, to be able to share data with many other applications.

XML is Human-Readable

XML documents are (or can be) read by people. Perhaps this doesn't sound so exciting, but compare it to data stored in a database. It is not easy to browse through a database and read different segments of it as you would a text file. Take a look at the XML document below.

Code Sample: XMLBasics/Demos/Paul.xml

<?xml version="1.0"?>
<person>
 <name>
  <firstname>Paul</firstname>
  <lastname>McCartney</lastname>
 </name>
 <job>Singer</job>
 <gender>Male</gender>
</person>
Code Explanation
It is not hard to tell from looking at this that the XML is describing a person named Paul McCartney, who is a singer and is male.
Do people read XML documents? Programmers do (hey, we're people too!). And it is easier for us if the documents we work with are easy to read.

XML is Free

XML doesn't cost anything to use. It can be written with a simple text editor or one of the many freely available XML authoring tools, such as XML Notepad. In addition, many web development tools, such as Dreamweaver and Visual Studio .NET have built-in XML support. There are also many free XML parsers, such as Microsoft's MSXML (downloadable from microsoft.com) and Xerces (downloadable at apache.org).

XML in Practice

Content Management

Almost all of the leading content management systems use XML in one way or another. A typical use would be to store a company's marketing content in one or more XML documents. These XML documents could then be transformed for output on the Web, as Word documents, as PowerPoint slides, in plain text, and even in audio format. The content can also easily be shared with partners who can then output the content in their own formats.
Storing the content in XML makes it much easier to manage content for two reasons.
  1. Content changes, additions, and deletions are made in a central location and the changes will cascade out to all formats of presentation. There is no need to be concerned about keeping the Word documents in sync with the website, because the content itself is managed in one place and then transformed for each output medium.
  2. Formatting changes are made in a central location. To illustrate, suppose a company had many marketing web pages, all of which were produced from XML content being transformed to HTML. The format for all of these pages could be controlled from a single XSLT and a sitewide formatting change could be made modifying that XSLT.

Web Services

XML Web services are small applications or pieces of applications that are made accessible on the Internet using open standards based on XML. Web services generally consist of three components:
  • SOAP - an XML-based protocol used to transfer Web services over the Internet.
  • WSDL (Web Services Description Language) - an XML-based language for describing a Web service and how to call it.
  • Universal Discovery Description and Integration (UDDI) - the yellow pages of Web services. UDDI directory entries are XML documents that describe the Web services a group offers. This is how people find available Web services.

RDF / RSS Feeds

RDF (Resource Description Framework) is a framework for writing XML-based languages to describe information on the Web (e.g, web pages). RSS (RDF Site Summary) is an implementation of this framework; it is a language that adheres to RDF and is used to describe web content. Website publishers can use RSS to make content available as a "feed", so that web users can access some of their content without actually visiting their site. Often, RSS is used to provide summaries with links to the company's website for additional information.

XML Documents

An XML document is made up of the following parts.
  • An optional prolog.
  • A document element, usually containing nested elements.
  • Optional comments or processing instructions.

The Prolog

The prolog of an XML document can contain the following items.
  • An XML declaration
  • Processing instructions
  • Comments
  • A Document Type Declaration

The XML Declaration

The XML declaration, if it appears at all, must appear on the very first line of the document with no preceding white space. It looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
This declares that the document is an XML document. The version attribute is required, but the encoding and standalone attributes are not. If the XML document uses any markup declarations that set defaults for attributes or declare entities then standalone must be set to no.

Processing Instructions

Processing instructions are used to pass parameters to an application. These parameters tell the application how to process the XML document. For example, the following processing instruction tells the application that it should transform the XML document using the XSL stylesheet beatles.xsl.
<?xml-stylesheet href="beatles.xsl" type="text/xsl"?>
As shown above, processing instructions begin with and <? end with ?>.

Comments

Comments can appear throughout an XML document. Like in HTML, they begin with <!-- and end with -->.
<!--This is a comment-->

A Document Type Declaration

The Document Type Declaration (or DOCTYPE Declaration) has three roles.
  1. It specifies the name of the document element.
  2. It may point to an external Document Type Definition (DTD).
  3. It may contain an internal DTD.
The DOCTYPE Declaration shown below simply states that the document element of the XML document is beatles.
<!DOCTYPE beatles>
If a DOCTYPE Declaration points to an external DTD, it must either specify that the DTD is on the same system as the XML document itself or that it is in some public location. To do so, it uses the keywords SYSTEM and PUBLIC. It then points to the location of the DTD using a relative Uniform Resource Indicator (URI) or an absolute URI. Here are a couple of examples.
Syntax
<!--DTD is on the same system as the XML document-->
<!DOCTYPE beatles SYSTEM "dtds/beatles.dtd">
Syntax
<!--DTD is publicly available-->
<!DOCTYPE beatles PUBLIC "-//Webucator//DTD Beatles 1.0//EN"
     "http://www.webucator.com/beatles/DTD/beatles.dtd">
As shown in the second declaration above, public identifiers are divided into three parts:
  1. An organization (e.g, Webucator)
  2. A name for the DTD (e.g, Beatles 1.0)
  3. A language (e.g, EN for English)

Elements

Every XML document must have at least one element, called the document element. The document element usually contains other elements, which contain other elements, and so on. Elements are denoted with tags. Let's look again at the Paul.xml.

Code Sample: XMLBasics/Demos/Paul.xml

<?xml version="1.0"?>
<person>
 <name>
  <firstname>Paul</firstname>
  <lastname>McCartney</lastname>
 </name>
 <job>Singer</job>
 <gender>Male</gender>
</person>
Code Explanation
The document element is person. It contains three elements: name, job and gender. Further, the name element contains two elements of its own: firstname and lastname. As you can see, XML elements are denoted with tags, just as in HTML. Elements that are nested within another element are said to be children of that element.

Empty Elements

Not all elements contain other elements or text. For example, in XHTML, there is an img element that is used to display an image. It does not contain any text or elements within it, so it is called an empty element. In XML, empty elements must be closed, but they do not require a separate close tag. Instead, they can be closed with a forward slash at the end of the open tag as shown below.
<img src="images/paul.jpg"/>
The above code is identical in funciton to the code below.
<img src="images/paul.jpg"></img>

Attributes

XML elements can be further defined with attributes, which appear inside of the element's open tag as shown below.
Syntax
<name title="Sir">
 <firstname>Paul</firstname>
 <lastname>McCartney</lastname>
</name>

CDATA

Sometimes it is necessary to include sections in an XML document that should not be parsed by the XML parser. These sections might contain content that will confuse the XML parser, perhaps because it contains content that appears to be XML, but is not meant to be interpreted as XML. Such content must be nested in CDATA sections. The syntax for CDATA sections is shown below.
Syntax
<![CDATA[
 This section will not get parsed
 by the XML parser.
]]>

White Space

In XML data, there are only four white space characters.
  1. Tab
  2. Line-feed
  3. Carriage-return
  4. Single space
There are several important rules to remember with regards to white space in XML.
  1. White space within the content of an element is significant; that is, the XML processor will pass these characters to the application or user agent.
  2. White space in attributes is normalized; that is, neighboring white spaces are condensed to a single space.
  3. White space in between elements is ignored.

xml:space Attribute

The xml:space attribute is a special attribute in XML. It can only take one of two values: default and preserve. This attribute instructs the application how to treat white space within the content of the element. Note that the application is not required to respect this instruction.

XML Syntax Rules

XML has relatively straightforward, but very strict, syntax rules. A document that follows these syntax rules is said to be well-formed.
  1. There must be one and only one document element.
  2. Every open tag must be closed.
  3. If an element is empty, it still must be closed.
    • Poorly-formed: <tag>
    • Well-formed: <tag></tag>
    • Also well-formed: <tag />
  4. Elements must be properly nested.
    • Poorly-formed: <a><b></a></b>
    • Well-formed: <a><b></b></a>
  5. Tag and attribute names are case sensitive.
  6. Attribute values must be enclosed in single or double quotes.

Special Characters

There are five special characters that can not be included in XML documents. These characters are replaced with predefined entity references as shown in the table below.
Special Characters
Character Entity Reference
< &lt;
> &gt;
& &amp;
" &quot;
' &apos;

Creating a Simple XML File

The following is relatively simple XML file describing the Beatles.

Code Sample: XMLBasics/Demos/Beatles.xml

<?xml version="1.0"?>
<beatles>
 <beatle link="http://www.paulmccartney.com">
  <name>
   <firstname>Paul</firstname>
   <lastname>McCartney</lastname>
  </name>
 </beatle>
 <beatle link="http://www.johnlennon.com">
  <name>
   <firstname>John</firstname>
   <lastname>Lennon</lastname>
  </name>
 </beatle>
 <beatle link="http://www.georgeharrison.com">
  <name>
   <firstname>George</firstname>
   <lastname>Harrison</lastname>
  </name>
 </beatle>
 <beatle link="http://www.ringostarr.com">
  <name>
   <firstname>Ringo</firstname>
   <lastname>Starr</lastname>
  </name>
 </beatle>
 <beatle link="http://www.webucator.com" real="no">
  <name>
   <firstname>Nat</firstname>
   <lastname>Dunn</lastname>
  </name>
 </beatle>
</beatles>
  1. Open XMLBasics/Exercises/Xml101.xml
  2. Add a required prerequisite: "Experience with computers".
  3. Add the following to the topics list:
    • XML Documents
      • The Prolog Elements
      • Attributes
      • CDATA
      • XML Syntax Rules
      • Special Characters
    • Creating a Simple XML File
  4. Add a modifications element that shows the modifications you've made.

Code Sample: XMLBasics/Exercises/Xml101.xml

<?xml version="1.0"?>
<course>
 <head>
  <title>Introduction to XML</title>
  <course_num>XML101</course_num>
  <course_length>3 days</course_length>
 </head>
 <body>
  <prerequisites>
   <prereq>Experience with Word Processing</prereq>
   <prereq optional="true">Experience with HTML</prereq>
   <!-- Add a required prerequisite: "Experience with computers"  -->
  </prerequisites>
  <outline>
   <topics>
    <topic>XML Basics
     <topics>
      <topic>What is XML?</topic>
      <topic>XML Benefits
       <topics>
        <topic>XML Holds Data, Nothing More</topic>
        <topic>XML Separates Structure from Formatting</topic>
        <topic>XML Promotes Data Sharing</topic>
        <topic>XML is Human-Readable</topic>
        <topic>XML is Free</topic>
       </topics>
      </topic>
      <!-- 
       Add the following to the topics list ("XML Documents" and "Creating a Simple XML File" should be siblings of "What is XML?" and "XML Benefits"):
       
       -XML Documents
        -The Prolog
        -Elements
        -Attributes
        -CDATA
        -XML Syntax Rules
        -Special Characters
       -Creating a Simple XML File
       -->
     </topics>
    </topic>
   </topics>
  </outline>
 </body>
 <foot>
  <creator>Josh Lockwood</creator>
  <date_created>2002-07-25</date_created>
  <modifications madeby="Colby Germond" date="2003-05-05">
   <modification type="insert">Added HTML prerequisite</modification>
   <modification type="edit">Fixed some typos</modification>
  </modifications>
  <!-- 
   Add a modifications element that shows the modifications you've made.
   -->
 </foot>
</course>

XML Schema Tutorial

The Purpose of XML Schema XML Schema is an XML-based language used to create XML-based languages and data models. An XML schema defines element and attribute names for a class of XML documents. The schema also specifies the structure that those documents must adhere to and the type of content that each element can hold.
XML documents that attempt to adhere to an XML schema are said to be instances of that schema. If they correctly adhere to the schema, then they are valid instances. This is not the same as being well formed. A well-formed XML document follows all the syntax rules of XML, but it does necessarily adhere to any particular schema. So, an XML document can be well formed without being valid, but it cannot be valid unless it is well formed.

The Power of XML Schema

You may already have some experience with DTDs. DTDs are similar to XML schemas in that they are used to create classes of XML documents. DTDs were around long before the advent of XML. They were originally created to define languages based on SGML, the parent of XML. Although DTDs are still common, XML Schema is a much more powerful language.
As a means of understanding the power of XML Schema, let's look at the limitations of DTD.
  1. DTDs do not have built-in datatypes.
  2. DTDs do not support user-derived datatypes.
  3. DTDs allow only limited control over cardinality (the number of occurrences of an element within its parent).
  4. DTDs do not support Namespaces or any simple way of reusing or importing other schemas.

A First Look

An XML schema describes the structure of an XML instance document by defining what each element must or may contain. An element is limited by its type. For example, an element of complex type can contain child elements and attributes, whereas a simple-type element can only contain text. The diagram below gives a first look at the types of XML Schema elements.
Schema authors can define their own types or use the built-in types. Throughout this course, we will refer back to this diagram as we learn to define elements. You may want to bookmark this page, so that you can easily reference it.
The following is a high-level overview of Schema types.
  1. Elements can be of simple type or complex type.
  2. Simple type elements can only contain text. They can not have child elements or attributes.
  3. All the built-in types are simple types (e.g, xs:string).
  4. Schema authors can derive simple types by restricting another simple type. For example, an email type could be derived by limiting a string to a specific pattern.
  5. Simple types can be atomic (e.g, strings and integers) or non-atomic (e.g, lists).
  6. Complex-type elements can contain child elements and attributes as well as text.
  7. By default, complex-type elements have complex content, meaning that they have child elements.
  8. Complex-type elements can be limited to having simple content, meaning they only contain text. They are different from simple type elements in that they have attributes.
  9. Complex types can be limited to having no content, meaning they are empty, but they have may have attributes.
  10. Complex types may have mixed content - a combination of text and child elements.

A Simple XML Schema

Let's take a look at a simple XML schema, which is made up of one complex type element with two child simple type elements.

Code Sample: SchemaBasics/Demos/Author.xsd

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="Author">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="FirstName" type="xs:string" />
        <xs:element name="LastName" type="xs:string" />
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
Code Explanation
As you can see, an XML schema is an XML document and must follow all the syntax rules of any other XML document; that is, it must be well formed. XML schemas also have to follow the rules defined in the "Schema of schemas," which defines, among other things, the structure of and element and attribute names in an XML schema.
Although it is not required, it is a common practice to use the xs qualifier (see footnote) to identify Schema elements and types.
The document element of XML schemas is xs:schema. It takes the attribute xmlns:xs with the value of http://www.w3.org/2001/XMLSchema, indicating that the document should follow the rules of XML Schema. This will be clearer after you learn about namespaces.
In this XML schema, we see a xs:element element within the xs:schema element. xs:element is used to define an element. In this case it defines the element Author as a complex type element, which contains a sequence of two elements: FirstName and LastName, both of which are of the simple type, string.

Validating an XML Instance Document

In the last section, you saw an example of a simple XML schema, which defined the structure of an Author element. The code sample below shows a valid XML instance of this XML schema.

Code Sample: SchemaBasics/Demos/MarkTwain.xml

<?xml version="1.0"?>
<Author xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:noNamespaceSchemaLocation="Author.xsd">
    <FirstName>Mark</FirstName>
    <LastName>Twain</LastName>
</Author>
Code Explanation
This is a simple XML document. Its document element is Author, which contains two child elements: FirstName and LastName, just as the associated XML schema requires.
The xmlns:xsi attribute of the document element indicates that this XML document is an instance of an XML schema. The document is tied to a specific XML schema with the xsi:noNamespaceSchemaLocation attribute.
There are many ways to validate the XML instance. If you are using an XML authoring tool, it very likely is able to perform the validation for you. Alternatively, a couple of simple online XML Schema validator tools are listed below.

JavaScript Tutorial

In this manual, we refer to the language we are learning as JavaScript, which is what it is usually called. However, the name JavaScript is owned by Netscape. Microsoft calls its version of the language JScript. The generic name of the language is EcmaScript.

The HTML DOM

The HTML Document Object Model (DOM) is the browser's view of an HTML page as an object hierarchy, starting with the browser window itself and moving deeper into the page, including all of the elements on the page and their attributes. Below is a simplified version of the HTML DOM.
As shown, the top-level object is window. The document object is a child of window and all the objects (i.e, elements) that appear on the page (e.g, forms, links, images, tables, etc.) are descendants of the document object. These objects can have children of their own. For example, form objects generally have several child objects, including textboxes, radio buttons, and select menus.

JavaScript Syntax

Basic Rules

  1. JavaScript statements end with semi-colons.
  2. JavaScript is case sensitive.
  3. JavaScript has two forms of comments:
    • Single-line comments begin with a double slash (//).
    • Multi-line comments begin with "/*" and end with "*/".
Syntax
// This is a single-line comment

/*
 This is
 a multi-line
 comment.
*/

Dot Notation

In JavaScript, objects can be referenced using dot notation, starting with the highest-level object (i.e, window). Objects can be referred to by name or id or by their position on the page. For example, if there is a form on the page named "loginform", using dot notation you could refer to the form as follows:
Syntax
window.document.loginform
Assuming that loginform is the first form on the page, you could also refer to this way:
Syntax
window.document.forms[0]
A document can have multiple form elements as children. The number in the square brackets ([]) indicates the specific form in question. In programming speak, every document object contains an array of forms. The length of the array could be zero (meaning there are no forms on the page) or greater. In JavaScript, arrays are zero-based, meaning that the first form on the page is referenced with the number zero (0) as shown in the syntax example above.

Square Bracket Notation

Objects can also be referenced using square bracket notation as shown below.
Syntax
window['document']['loginform']

// and 

window['document']['forms[0]']
Dot notation and square bracket notation are completely interchangeable. Dot notation is much more common; however, as we will see later in the course, there are times when it is more convenient to use square bracket notation.

Where Is JavaScript Code Written?

JavaScript code can be written inline (e.g, within HTML tags called event handlers), in script blocks, and in external JavaScript files. The page below shows examples of all three.

Code Sample: JavaScriptBasics/Demos/JavaScript.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  window.alert("The page is loading");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = 'red';">Red</span> |
 <span onclick="document.bgColor = 'white';">White</span>
</p>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>

Code Sample: JavaScriptBasics/Demos/Script.js

document.write("Hello, there!");
Code Explanation
As this page loads, an alert will pop up that says "The page is loading" as shown below.
After the user clicks the OK button, the page will finish loading and will appear as follows.
The text "Hello, there!" is written dynamically by the code in JavaScriptBasics/Demos/Script.js. We will look at the code in this file and in JavaScriptBasics/Demos/JavaScript.html again shortly.

JavaScript Objects, Methods and Properties

JavaScript is used to manipulate or get information about objects in the HTML DOM. Objects in an HTML page have methods (actions, such as opening a new window or submitting a form) and properties (attributes or qualities, such as color and size).
To illustrate objects, methods and properties, we will look at the code in JavaScriptBasics/Demos/JavaScript2.html, a slightly modified version of JavaScriptBasics/Demos/JavaScript.html, which we looked at earlier, and at the code in JavaScriptBasics/Demos/Script2.js.

Code Sample: JavaScriptBasics/Demos/JavaScript2.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  //Pop up an alert
  window.alert("The page is loading");
 </script>
</head>
<body>
<p align="center">
 <span onclick="document.bgColor = 'red';">Red</span> |
 <span onclick="document.bgColor = 'white';">White</span> |
 <span onclick="document.bgColor = 'green';">Green</span> |
 <span onclick="document.bgColor = 'blue';">Blue</span>
</p>
<script type="text/javascript" src="Script2.js"></script>
</body>
</html>

Code Sample: JavaScriptBasics/Demos/Script2.js

/*
This script simply outputs
 "Hello, there!"
to the browser.
*/
document.write("Hello, there!");

Methods

Methods are the verbs of JavaScript. They cause things to happen.

window.alert()

HTML pages are read and processed from top to bottom. The JavaScript code in the initial script block at the top of JavaScriptBasics/Demos/JavaScript2.html calls the alert() method of the window object. When the browser reads that line of code, it will pop up an alert box and will not continue processing the page until the user presses the OK button. Once the user presses the button, the alert box disappears and the rest of the page loads.

document.write()

The write() method of the document object is used to write out code to the page as it loads. In JavaScriptBasics/Demos/Script2.js, it simply writes out "Hello, there!"; however, it is more often used to write out dynamic data, such as the date and time on the user's machine.

Arguments

Methods can take zero or more arguments separated by commas.
Syntax
object.method(argument1, argument2);
The alert() and write() methods shown in the example above each take only one argument: the message to show.

Properties

Properties are the adjectives of JavaScript. They describe qualities of objects and, in some cases are writable (can be changed dynamically).

document.bgColor

The bgColor property of the document object is read-write. Looking back at JavaScriptBasics/Demos/JavaScript2.html, the four span elements use the onclick event handler to catch click events. When the user clicks on a span, JavaScript is used to change the value of the bgColor property to a new color.

The Implicit window Object

The window object is always the implicit top-level object and therefore does not have to be included in references to objects. For example, window.document.write() can be shortened to document.write(). Likewise, window.alert() can be shortened to just alert().

The getElementById() Method

A very common way to reference HTML elements is by their ID using the getElementById() method of the document object as shown in the example below.

Event Handlers

In JavaScriptBasics/Demos/JavaScript2.html, we used the onclick event handler to call JavaScript code that changed the background color of the page. Event handlers are attributes that force an element to "listen" for a specific event to occur. Event handlers all begin with the letters "on". The table below lists the HTML event handlers with descriptions.
HTML Event Handlers
Event Handler Elements Supported Description
onblur a, area, button, input, label, select, textarea the element lost the focus
onchange input, select, textarea the element value was changed
onclick All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was clicked
ondblclick All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was double clicked
onfocus a, area, button, input, label, select, textarea the element received the focus
onkeydown All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was pressed down
onkeypress All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was pressed and released
onkeyup All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a key was released
onload frameset all the frames have been loaded
onload body the document has been loaded
onmousedown All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was pressed down
onmousemove All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved within
onmouseout All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved away
onmouseover All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer was moved onto
onmouseup All elements except applet, base, basefont, bdo, br, font, frame, frameset, head, html, iframe, isindex, meta, param, script, style, title a pointer button was released
onreset form the form was reset
onselect input, textarea some text was selected
onsubmit form the form was submitted
onunload frameset all the frames have been removed
onunload body the document has been removed
Duration: 15 to 25 minutes.
In this exercise, you will use some of the event handlers from the table above to allow the user to change the background color of the page.
  1. Open JavaScriptBasics/Exercises/JavaScript.html for editing.
  2. Modify the page so that...
    • when it is finished loading an alert pops up reading "The page has loaded!"
    • when the "Red" button is clicked, the background color turns red and an alert pops up reading "The background color is now Red."
    • when the "Green" button is double-clicked, the background color turns green and an alert pops up reading "The background color is now Green."
    • when the "Orange" button is clicked down, the background color turns orange and an alert pops up reading "The background color is now Orange."
    • when the mouse button is released over the "Blue" button, the background color turns blue and an alert pops up reading "The background color is now Blue."

Code Sample: JavaScriptBasics/Exercises/JavaScript.html

<html>
<head>
 <title>JavaScript Page</title>
 <script type="text/javascript">
  window.alert("The page is loading.");
 </script>
</head>
<body>
<form>
 Click the button to turn the page
 <input type="button" value="Red"/>
 <br/><br/>
 Double click the button to turn the page
 <input type="button" value="Green"/>
 <br/><br/>
 Click down on the button to turn the page
 <input type="button" value="Orange"/>
 <br/><br/>
 Release the mouse while on the button to turn the page
 <input type="button" value="Blue"/>
</form>
<hr/>
<script type="text/javascript" src="Script.js"></script>
</body>
</html>
  1. Add functionality so that when the user presses any key, the background color turns white.
  2. Add a "Black" button. When the user hovers over this button and presses the mouse button down, the background color should turn black. When the user releases the mouse button, the background color should turn white.

CSS Tutorial

CSS Rules

CSS rules are statements that define the style of an element or group of elements. The syntax is as follows:
Syntax
selector {property:value; property:value; property:value}
Each property:value pair is a declaration. Multiple declarations are separated by semi-colons. The selector defines which elements are affected by the rule. Take a look at the following rule.
p {
 color:darkgreen;
 font-family:Verdana;
 font-size:10pt
}
This rule specifies that all paragraph text should be darkgreen and use a 10-point Verdana font.

CSS Comments

Comments in CSS begin with "/*" and end with "*/". See the example below.
p {
 color:red; /* All paragraphs should be red */
}

Selectors

The are several different types of selectors:
  • Type
  • Descendant
  • Child
  • Class
  • ID
  • Attribute
  • Universal
Selectors identify the element(s) affected by the CSS rule. There are several different types of selectors, including type selectors, descendant selectors, class selectors, and ID selectors. (see footnote)

Type Selectors

Type selectors specify elements by tag name and affect every instance of that element type. Looking again at a previous example:
p {
 color:darkgreen;
 font-family:Verdana;
 font-size:10pt;
}
This rule specifies that the text of every <p> element should be darkgreen and use a 10-point Verdana font.

Descendant Selectors

Descendant selectors specify elements by ancestry. Each "generation" is separated by a space. For example, the following rule states that <strong> tags within <p> tags should have red text.
p strong {
 color:red;
}
With descendant selectors generations can be skipped. In other words, the code above does not require that the <strong> tag is a direct child of the <p> tag.

Child Selectors(see footnote)

Child selectors specify a direct parent-child relationship
p > strong {
 color:red;
}
In this case only <strong> tags that are direct children of <p> tags are affected.

Class Selectors

Almost all elements (see footnote) can take the class attribute, which assigns a class name to an element. Class names are created in style sheet with rules defined for class selectors. Class selectors begin with a dot and have arbitrary names. For example, the following rule creates a class called "warning," which makes the text of all elements of that class bold and red.
.warning {
 font-weight:bold;
 color:#ff0000;
}
Following are a couple of examples of elements of the warning class.
<h1 class="warning">WARNING</h1>
<p class="warning">Don't go there!</p>
If the class selector is preceded by an element name, then that selector only applies to the specified type of element. To illustrate, the following two rules indicate that h1 elements of the class "warning" will be underlined, while p elements of the class "warning" should not be.
h1.warning {
 color:#ff0000;
 text-decoration:underline
}
p.warning {
 color:#ff0000;
 font-weight:bold;
}
Because both rules indicate that the color should be red (#ff0000), this could be rewritten as follows.
.warning {
 color:#ff0000;
}
h1.warning {
 text-decoration:underline;
}
p.warning {
 font-weight:bold;
}
Note that you can assign an element any number of classes simply by separating the class names with spaces like this:
Syntax
<div class="class1 class2 class3">...

ID Selectors

As with the class attribute, almost all elements (see footnote) can take the id attribute, which is used to uniquely identify an element on the page. ID selectors begin with a pound sign (#) and have arbitrary names. The following rule will indent the element with the "maintext" id 20 pixels from the left and right.
#mainText {
 margin-left:20px;
 margin-right:20px;
}

<div id="mainText">
 This is the main text of the page...
</div>

Attribute Selectors(see footnote)

Attribute selectors specify elements that contain a specific attribute. They can also specify the value of that attribute.
The following selector affects all links with a target attribute.
a[target] {
 color:red;
}
The following selector would only affect links whose target attribute is "_blank".
a[target="_blank"] {
 color:red;
}

The Universal Selector

The unversal selector is an asterisk (*). It matches every element.
* {
 color:red;
}

Grouping

Selectors can share the same declarations by separating them with commas. The following rule will underline all i elements, all elements of the class "warning" and the element with the id of "important."
i, .warning, #important {
 text-decoration: underline;
}

Precedence of Selectors

In the event that rules conflict:
  • The rule with the more specific selector takes precedence.
  • In the event that two selectors have the same specificity, the rule specified later in the document takes precedence.

Determining a Selector's Specificity

Imagine your selectors are stacked as follows with the ones on top having the highest specificity:
  1. Declarations in the style attribute have no selector and have the highest precedence.
  2. Selectors with id attributes (e.g, h1#foo {}) have the next highest precedence.
  3. Selectors with other attributes (e.g., h1.foo and a[target]) or pseudo-classes (e.g, a:hover) have the next highest precedence.
  4. Selectors with element names (e.g, h1) but no other attributes have the next highest precedence.
  5. The universal selector (*) has the lowest precedence.
To figure out the exact specificity, follow this process:
  1. Start with 0,0,0,0.
  2. If the declaration is found in the style attribute, change the first digit to 1, giving you 1,0,0,0. In this case, you have the highest possible specificity and can stop calculating.
  3. For each time the condition in level 2 is met, add 1 to the second digit.
    • For example, for ol#foo li#bar add 2 (1 for each id), giving you 0,2,0,0.
  4. For each time the condition in level 3 is met, add 1 to the third digit.
    • For example, for ol#foo li#bar a[target] add 1, giving you 0,2,1,0.
  5. For each time the condition in level 4 is met, add 1 to the fourth digit.
    • For example, for ol#foo li#bar a[target] add 3 (1 for each element name), giving you 0,2,1,3.
When comparing two selectors' specificity, start with the left-most numbers. If one has a higher number than the other, than it is more specific. If they are the same, look to the next number and so on.

The Cascade

Web designers can define style rules in three different places:
  1. In an embedded style sheet.
  2. In an external (or linked or imported) style sheet.
  3. Inline in an element.

Embedded Style Sheets

Embedded style sheets appear in the style element in the head of an HTML page. The code below shows a page with an embedded style sheet.

Code Sample: CrashCourse/Demos/EmbeddedStyleSheet.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Embedded Style Sheet</title>
<style type="text/css">
 .warning {color:#ff0000}
 h1.warning {text-decoration:underline}
 p.warning {font-weight:bold}
</style>
</head>
<body>
<h1 class="warning">WARNING</h1>
<p class="warning">Don't go there!</p>
</body>
</html>
Code Explanation
As you can see, the <style> tag takes the type attribute, which is used to indicate that this is a CSS style sheet. This page will render as follows:

Exercise: Creating an Embedded Style Sheet

Duration: 20 to 30 minutes.
In this exercise, you will add an embedded style sheet to CrashCourse/Exercises/EmbeddedStyleSheet.html. You will be adding several rules to a simple HTML file. Do not worry about learning the CSS properties and values at this point. This exercise is just to give you some practice creating a style sheet.
  1. Open CrashCourse/Exercises/EmbeddedStyleSheet.html in a browser. It should look like this.
  2. Open CrashCourse/Exercises/EmbeddedStyleSheet.html for editing.
  3. Add a style block in the head of the page. Don't forget to include the type attribute.
  4. Add a rule for the body element that contains the following property-value pairs:
    • background-image:url('Images/Baseball.gif');
    • background-repeat:repeat-x;
    • background-position:bottom;
    • margin-left:50%;
    • margin-top:20px;
  5. Add a rule for div elements that contains the following property-value pairs:
    • padding:10px;
    • border:10px groove red;
    • width:300px;
    • background-image:url('Images/YankeeStadium.gif');
    • margin-left:-170px;
  6. Add a rule for h1 elements that contains the following property-value pairs:
    • text-align:center;
    • font-size: 12pt;
    • color:#000099;
    • margin-bottom:5px;
    • text-decoration:underline;
  7. Add a rule for table elements that contains the following property-value pairs:
    • margin:5px;
    • width:290px;
  8. Add a rule for th elements that contains the following property-value pairs:
    • margin:5px;
  9. Add a rule for td elements that contains the following property-value pairs:
    • padding-left:8px;
    • padding-right:8px;
    • border:1px solid #990000;
    • background-color:#ffffcc;
  10. Assign an id of "trHeader" to the first table row and add a rule for this id that contains the following property-value pairs:
    • text-decoration:underline;
    • color:#990000;
  11. Assign a class called "centerCell" to all of the center table data cells and add a rule for this class that contains the following property-value pairs:
    • text-align:center;
  12. Re-open EmbeddedStyleSheet.html in a browser. It should look like this:

External Style Sheets

External style sheets are created in separate documents with a ".css" extension. An external style sheet is simply a listing of rules. It cannot contain HTML tags. CrashCourse/Demos/Stylesheet.css is an example of an external style sheet.

Code Sample: CrashCourse/Demos/StyleSheet.css

.warning {color:#ff0000}
h1.warning {text-decoration:underline}
p.warning {font-weight:bold}
Code Explanation
The above CSS file can be included in any number of HTML pages. The <link> tag, which goes in the head of an HTML page, is used to link to an external style sheet.

Code Sample: CrashCourse/Demos/ExternalStyleSheet.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>External Style Sheet</title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1 class="warning">WARNING</h1>
<p class="warning">Don't go there!</p>
</body>
</html>
<link> Attributes
Attributed Description
href points to the location of the external style sheet
rel must be set to "stylesheet" for linking style sheets
type must be set to "text/css" for linking to cascading style sheets
There is no limit to the number of external style sheets a single HTML page can use. Also, external style sheets can be combined with embedded style sheets.

Exercise: Creating an External Style Sheet

Duration: 5 to 10 minutes.
In this exercise, you will extract the embedded stylesheet that you created in the last exercise to a new external style sheet.
  1. Open CrashCourse/Exercises/EmbeddedStyleSheet.html in your editor and save it as LinkedStyleSheet.html.
  2. Create a new file and save it as StyleSheet.css in the same directory.
  3. Move all the CSS rules from LinkedStyleSheet.html to StyleSheet.css.
  4. In LinkedStyleSheet.html, remove the style block and add a link tag that points to StyleSheet.css.
  5. Open LinkedStyleSheet.html in a browser. It should look the same as EmbeddedStyleSheet.html.

Inline Styles

Inline styles are created by adding the style attribute to a tag. As with the class and id attributes, almost all elements (see footnote) can take the style attribute. The value of the style attribute is a list of one or more property-value pairs separated by semi-colons. The code sample below illustrates how inline styles are used.

Code Sample: CrashCourse/Demos/InlineStyles.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Inline Styles</title>
</head>
<body>
<p style="color:blue; font-weight:bold; font-size:12pt">Common Greetings</p>
<ul style="margin-top:-20px; font-size:10pt">
 <li style="list-style-type:square">Hello</li>
 <li style="list-style-type:circle">Hi</li>
 <li style="list-style-type:disc">Howdy</li>
</ul>
</body>
</html>
Code Explanation
This page will render as follows.

Exercise: Adding Inline Styles

Duration: 10 to 20 minutes.
In this exercise, you will add some inline styles to the page you have been working on.
  1. Open CrashCourse/Exercises/LinkedStyleSheet.html and save it as InlineStyles.html.
  2. Add an inline style to the table data cell containing the word "Braves". The style should contain the following property-value pairs:
    • font-style: italic;
    • color: #ff0000;
  3. Add an inline style to the table data cell containing the word "Yankees". The style should contain the following property-value pairs:
    • font-style: italic;
    • color: #000033;
  4. Add inline styles to the table data cells containing the word "Giants". The style should contain the following property-value pairs:
    • font-style: italic;
    • color: #cc3300;
  5. Open InlineStyles.html in a browser. It should look like this:

Media Types

Styles can be defined for different media. For example, you may want to style a page one way for viewing with a browser and a different way for viewing in print. The media type is defined in the <link> tag for external style sheets and in the <style> tag for embedded style sheets.
Syntax
<link href="stylesheet.css" rel="stylesheet" type="text/css" media="screen">

<style type="text/css" media="all">
 /* rules */
</style>
If the media is undefined then the style rules will apply to all media. Possible values for media are:
  • all
  • aural
  • braille
  • embossed
  • handheld
  • print
  • projection
  • screen
  • tty
  • tv
The following code sample illustrates how you can use CSS to design for different media.

Code Sample: CrashCourse/Demos/Media.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS Media</title>
<style type="text/css" media="screen">
 .warning {color:#ff0000}
 h1.warning {text-decoration:underline}
 p.warning {font-weight:bold}
 .printDisplay {display:none}
</style>
<style type="text/css" media="print">
 .warning {color:#660000;}
 h1.warning {text-decoration:underline; font-size:1in;}
 p.warning {font-weight:bold; font-size:.5in;}
 .screenDisplay {display:none}
</style>
</head>
<body>
<h1 class="warning">WARNING</h1>
<p class="warning">Don't go there!</p>
<p class="printDisplay">This is the print version.</p>
<p class="screenDisplay">This is the screen version.</p>
</body>
</html>
Code Explanation
As shown below, the screen output of the file above is different from the print output.
The screen output will look like this:
The print output will look like this:

<div> and <span>

The <div> and <span> tags are used in conjunction with Cascading Style Sheets. By themselves, they do very little. In fact, the <span> tag has no visual effect on its contents. The only effect of the <div> tag is to block off its contents, similar to putting a <br> tag before and after a section on the page.
Like most tags, the <div> and <span> tag can take the class, id, and style attributes. It is through these attributes that styles are applied to the elements. The tags are used like any other HTML tags and can be nested within each other any number levels.

Code Sample: CrashCourse/Demos/DivAndSpan.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Div and Span</title>
</head>
<body>
<div style="position:absolute; left:0px; top:0px; 
 font-family:Verdana; font-size:10pt;
 border-style:groove; border-width:30px; border-color:blue; padding:4px">
This text appears in the 
 <span style="font-style:italic; color:red">upper-left hand corner</span>
 of the page.<br />
 It also has a big blue groovy border around it.
</div>
</body>
</html>
Code Explanation
This page will render as follows.

Exercise: Divs and Spans

Duration: 10 to 20 minutes.
In this exercise, you will add class and id attributes to div and span tags to an already existing HTML page. The HTML page already contains an embedded style sheet, which you will not need to modify. Your goal is to make the page render as follows.
There are no step by step instructions. Review the rules in the embedded style sheet and apply classes and ids as appropriate.

Units of Measurement

CSS allows you to specify font size, border size, margins, padding, etc. using many different units of measurement. The table below shows the units available.
Unit Description Example
px Pixels margin-top: 10px;
pt Points font-size: 12pt;
in Inches padding-top: .5in;
cm Centimeters top: 5cm;
mm Millimeters left: 45mm;
pc Picas bottom: 12pc;
em Ems font-size: 1.5em;
ex Exs font-size: 1.5ex;
% Percentage width: 80%;

Pixels (px)

The measurement unit most often used for designing web pages is pixels. A pixel is not an absolute measurement like, for example, an inch or a point. The actual size of a pixel depends on the resolution and size of a user's monitor. Consider an image that is 900 pixels wide. If the monitor resolution is set to 800 by 600 pixels, then the image will not fit on the screen. However, if the monitor resolution on the same computer is set to 1024 by 768 pixels, the image will fit with room to spare.

Points (pt)

Points should be reserved for print. There are 72 points in an inch.

Inches (in), Centimeters (cm), and Millimeters (mm)

Although these are the most common units of measurement in life, they should be avoided in Web design.

Picas (pc)

Picas should be reserved for print. There are 6 picas in an inch.

Ems (em)

An em (or Mutt) is a relative unit that refers to the size of the letter "M" in a font. Because em is a relative rather than absolute measurement, it is often used in Web design.

Exs (ex)

The "x-height" is the height of font's lowercase "x". Exs are used to set the size of content based on the size of the surrounding font.

The Inherit Value

Many properties take the value inherit. This specifies that the property value should be inherited from the parent element. If such a property is left undefined, the implicit value is inherit.

@import

The @import rule is used to import one style sheet into another. There are two syntaxes for using @import:
Syntax
@import "styles.css" mediatypes;
@import url("styles.css") mediatypes;
In the examples above, mediatypes would be replaced by a comma-delimited list of media types to which the imported style sheet applies.

How ColdFusion Works

ColdFusion MX 7 code is compiled into Java bytecode, making it extremely portable, flexible and powerful. ColdFusion is made up of two parts:
  1. ColdFusion Application Server
  2. ColdFusion Markup Language (CFML)

ColdFusion Application Server

When a user navigates in a browser to a page that ends with a .cfm extension, the request is sent to a Web server, which directs the request to the ColdFusion Application Server (CFAS).
As shown in the diagram above, the CFAS processes the page, communicating with the file systems, databases, and email servers as necessary, and then delivers a web page to the web server to return to the browser.

ColdFusion Markup Language

The ColdFusion Markup Language (CFML) looks very similar to HTML or XML in that it is tag-based. A ColdFusion page generally has a mix of HTML and ColdFusion tags, and may contain other tags as well. ColdFusion tags can be distinguished from all other tags by their first two letters - cf (e.g, <cfloop>).

ColdFusion Variables

ColdFusion is weakly typed, meaning that you do not have to specify the data type that a variable holds. Rather, ColdFusion determines the data type of a variable at the time the variable is used. A common way to set a variable is with the <cfset> tag.
<cfset firstname = "Paul">
<cfset age = 63>

Variable Names

In ColdFusion, variable names:
  • consist of letters, digits, underscores, and dollar signs
  • cannot begin with a digit
  • are case-insensitive

Variable Prefixes and Scope

There are many different flavors of variables in ColdFusion:
  • variables specific to a page
  • variables specific to a user's session
  • variables specific to an entire application
  • etc.
These flavors of variables each have a different scope, which determines where and how long a variable exists. For example, variables specific to a user's session are of the Session scope. They exist for the duration of the session and are accessible on every page that is a part of the session. Variables specific to a page (i.e, Local variables) are of the Variables scope.
A prefix is used to specify the scope of a variable. The syntax is shown below.
Syntax
SCOPE.VariableName
The following table shows several variable scopes and their prefixes. Prefixes are not required for variables of all scopes. Required prefixes are in bold.
Variable Scope
Scope Prefix Description
Local VARIABLES Defined and accessible on the current page only.
CGI CGI Accessible on any page. Contains server environment variables.
URL URL Accessible on the current page. Contains values passed in on the query string.
Form FORM Accessible on the current page. Contains values passed in through a form.
Cookie COOKIE Accessible on any page. Contains variables held in cookies on the client machine.
Client CLIENT Accessible on any page. Contains variables created using the Client prefix.
Arguments ARGUMENTS Defined and accessible within a user-defined function or a ColdFusion Component method.
Session SESSION Prefix Required. Accessible on any page to a single user for the duration of a client session.
Application APPLICATION Prefix Required. Accessible on any page to all users until the application is restarted.
Server SERVER Prefix Required. Accessible on any page that is delivered from specific server.
Variables of different scopes can have the same names. For example, a local variable could have the same name as a form variable. If such a variable is referred to without a prefix, ColdFusion needs to know which variable to use. ColdFusion will search through the scopes in the following order:
  1. Arguments
  2. Local (Variables)
  3. CGI
  4. URL
  5. Form
  6. Cookie
  7. Client
In general, it is a good idea to include the prefix when referring to variables as this will help avoid confusion and could make the page process more quickly as ColdFusion will know exactly where to look for the variable.

Using <cfoutput>

A ColdFusion page is generally a mixture of CFML tags, HTML tags, and plain text. ColdFusion ignores any content that is not contained within a CFML tag. That is, content outside of CFML tags is returned as is to the browser.
The <cfoutput> tag is used to tell ColdFusion to attempt to evaluate any variable or expressions contained within pound signs (#). Let's take a look at an example. You guessed it - "Hello World".

Code Sample: Basics/Demos/HelloWorld.cfm

<cfset VARIABLES.greeting="Hello">

<html>
<head>
 <title>Hello World!</title>
</head>
<body>
 <cfoutput>#VARIABLES.greeting# World!</cfoutput>
</body>
</html>
Code Explanation
The code isn't very exciting. In fact, ColdFusion doesn't buy us anything here as we could have just as easily output the code using HTML. There is nothing dynamic about the script. Let's try something a little more interesting.

Passing Variables on the URL

A common way to pass values from the browser to the server is by appending them to the URL as follows:
http://webucator.com/hello.cfm?greet=Hello&person=World
   
The part of the url that follows the question mark is called the query string. One or more name-value pairs can be passed to the server in this way. Each name-value pair is separated by an ampersand (&). The processing page can read these name-value pairs and use them to determine its response.
The HTML page below shows an example of how these name-value pairs might be passed.

Code Sample: Basics/Demos/HelloHi.html

<html>
<head>
 <title>Preferred Greeting</title>
</head>
<body>
 Do you prefer a formal greeting or an informal greeting?
 <ul>
 <li><a href="HelloHi.cfm?greet=Hello">Formal</a></li>
 <li><a href="HelloHi.cfm?greet=Hi">Informal</a></li>
 <li><a href="HelloHi.cfm?greet=Howdy">Friendly</a></li>
 </ul>
</body>
</html>

Code Sample: Basics/Demos/HelloHi.cfm

<html>
<head>
 <title><cfoutput>#URL.greet#</cfoutput> World!</title>
</head>
<body>
<cfoutput>#URL.greet# World!</cfoutput>
</body>
</html>
Code Explanation
The <cfoutput> tags tell ColdFusion to look for variables and expressions to evaluate. Within <cfoutput> tags, any content not in pound signs (#) is simply ignored. Another way to write this page would be to replace the two sets of <cfoutput> tags with an open <cfoutput> tag before the open <html> tag and a close </cfoutput> tag after the close </html> tag.
Note that <cfoutput> tags, as a general rule, cannot be nested. (see footnote)

ColdFusion Comments

ColdFusion comments are similar to HTML comments except that they take three dashes instead of two.
<!-- This is an HTML comment -->
<!--- This is a ColdFusion comment --->


In this exercise, you will write a script that says hello to different people based on what is passed through the query string.
  1. Open Basics/Exercises/HelloWho.html in your editor.
  2. Modify HelloWho.html so that each Beatle name is a link passing the name of that Beatle (Paul, John, George or Ringo) to HelloWho.cfm.
  3. Open Basics/Exercises/HelloWho.cfm in your editor.
  4. Modify HelloWho.cfm so that it outputs a greeting based on the link that is clicked on HelloWho.html.
  5. Test your solution in a browser.

Code Sample: Basics/Exercises/HelloWho.html

<html>
<head>
 <title>Greeting the Beatles</title>
</head>
<body>
 Choose a Beatle to greet.
 <ul>
 <li><a href="HelloWho.cfm">Paul</a></li>
 <li><a href="HelloWho.cfm">John</a></li>
 <li><a href="HelloWho.cfm">George</a></li>
 <li><a href="HelloWho.cfm">Ringo</a></li>
 </ul>
</body>
</html>

Code Sample: Basics/Exercises/HelloWho.cfm

<html>
<head>
 <title></title>
</head>
<body>

</body>
</html>
Change the links so that each Beatle gets a custom greeting (e.g, Howdy Paul, Hi John, Bye George, Hey Ringo).

HTML Forms and ColdFusion Variables

How HTML Forms Work

A very common way to submit data to a web server is through HTML forms. There are two methods of submitting data through a form: the get method and the post method. The method used is determined by the value of the method attribute of the form tag. The default method is get.

Get Method

When the get method is used, data is sent to the server in name-value pairs as part of the query string. The get method is most commonly used by search pages and is useful when it is important to be able to bookmark the resulting page (i.e, the page that is returned after the form is submitted).

Post Method

When the post method is used, data is sent to the server in name-value pairs behind the scenes. The two major advantages of the post method are:
  1. The name-value pairs are not visible in the location bar, so sensitive data such as passwords are not displayed on the screen.
  2. Files, such as images and Office documents, can be uploaded via the form.
The major disadvantage is that the resulting page cannot be bookmarked.

A Sample HTML Form

The following is a sample HTML form for calculating the time it takes to run a specified distance at a specified speed.

Code Sample: Basics/Demos/Calculator.html

<html>
<head>
 <title>Marathon Time Calculator</title>
</head>
<body>

<h1>Marathon Time Calculator</h1>

<form method="post" action="ProcessCalculator.cfm">
<table>
<tr>
 <td>Your Name:</td>
 <td><input name="yourname" type="text" size="30"></td>
</tr>
<tr>
 <td>Your Speed:</td>
 <td><input name="yourspeed" type="text" size="4"></td>
</tr>
<tr valign="top">
 <td>Friend's Name:</td>
 <td><input name="friendname" type="text" size="30"></td>
</tr>
<tr>
 <td>Friend's Speed:</td>
 <td><input name="friendspeed" type="text" size="4"></td>
</tr>
<tr>
 <td>Units</td>
 <td>
  <select name="units">
   <option value="mph">MPH</option>
   <option value="kph">KPH</option>
  </select>
 </td>
</tr>
<tr>
 <td colspan="2" align="right">
  <input type="submit" value="Calculate">
 </td>
</tr>
</table>
</form>

</body>
</html>
Code Explanation
The above is a simple HTML form and contains no embedded ColdFusion code. Its action page is ProcessCalculator.cfm, which would contain ColdFusion code for processing the submitted form.

Exercise: Processing Form Input

Duration: 15 to 25 minutes.
Next we will create a page that processes the form data. Our form entry page, excalculator- simpleform1.html, is already complete and is identical to democalculator- simpleform1.html above. Filled out, it would look like this:
  1. Our form entry page, Basics/Exercises/Calculator.html, is already complete and is identical to Basics/Demos/Calculator.html above. Filled out, it would look like this:
  2. In this exercise, we will create a page that simply outputs the form entries as a list.
  3. Open Basics/Exercises/ProcessCalculator.cfm in your editor.
  4. Output the form variables as list items using <cfoutput>.
  5. Save your work and test your solution in the browser by navigating to Basics/Exercises/Calculator.html and submitting the form.

Code Sample: Basics/Exercises/ProcessCalculator.cfm

<html>
<head>
 <title>Calculator Entries</title>
</head>
<body>
<h1>Calculator Entries</h1>

You have entered:
<ul>
<!---
 Add list items that display your name,
 your friend's name, your speed,
 your friend's speed, and the units.
--->
</ul>

</body>
</html>

Built-in Functions

ColdFusion has many built-in functions for performing all sorts of tasks, such as manipulating strings, formatting data, managing dates and times, parsing XML, etc.
The syntax of a function is functionname(arguments), where arguments is a list of zero or more values passed to the function.
Like variables, function names are case-insensitive.
It is impossible (at least for this author) to memorize all the function names and the parameters that each function takes. So, every ColdFusion developer should have a good function reference. Following are few suggestions:

ColdFusion Function References

  • Dreamweaver's built-in Macromedia CF Function Reference, which you can get to by pressing shift+F1 or selecting Window > Reference.
  • Macromedia LiveDocs, where the functions are divided neatly into categories. The URL is http://livedocs.macromedia.com/coldfusion/7/htmldocs/00000354.htm
  • Macromedia ColdFusion MX 7 Web Application Construction Kit by Ben Forta and Nate Weiss has an excellent function reference in Appendix C.
We will be looking at many functions throughout this course, but to give you a feel for what they how they work, here are a few date and time functions.

Date & Time Functions

Function Description
Now() Returns the current date and time on the server.
DateFormat("date" [,"mask"]) Formats the date as specified by the mask.
TimeFormat("time" [,"mask"]) Formats the time as specified by the mask.
CreateDate(year, month, day) Creates a date/time object with the time set to 00:00:00.
IsDate(string) Returns true if a string can be converted to a valid date/time object.
DaysInMonth("date") Returns the number of days in a month.
The file below shows these functions in practice:

Code Sample: Basics/Demos/DateFunctions.cfm

<html>
<head>
<title>Date Functions</title>
</head>
<body>
<cfset RightNow = Now()>
<cfoutput>
 #RightNow#<br />
 #DateFormat(RightNow)#<br />
 #DateFormat(RightNow,"mm/dd/yy")#<br />
 #TimeFormat(RightNow)#<br />
 #TimeFormat(RightNow,"hh:mm tt")#<br />
 #IsDate(RightNow)#<br />
 #IsDate("January 31, 2007")#<br />
 #IsDate("foo")#<br />
 #DaysInMonth(RightNow)#
</cfoutput>
</body>
</html>
Code Explanation
The output is shown below:
And here is another demo showing a friendlier page using Now() and DateFormat():

Code Sample: Basics/Demos/HelloWorldDate.cfm

<cfset greeting="Hello">
<cfset today = Now()>

<html>
<head>
 <title>Hello World!</title>
</head>
<body>
 <cfoutput>
  #greeting#, World!<br>
  Today is #DateFormat(Now(),"dddd, mmmm d, yyyy")#.
 </cfoutput>
</body>
</html>
Code Explanation
The output is shown below:

Pound Sign Usage

You may notice that no pound signs are used around the Now() function in the <cfset> tag, while there are pound signs around the DateFormat() function. The use of pound signs to indicate that a variable or expression should be evaluated can be a bit confusing. Here are the rules:
  • Use pound signs when the expression to be evaluated is not within a ColdFusion tag (e.g, <cfoutput>#Now()#</cfoutput>.
  • Use pound signs around expressions that are within a ColdFusion tag ONLY when the expression is also in quotes (e.g, <cfset greeting = "Hello #person#">).
  • With nested functions, use pound signs only around the outermost function (e.g, <cfoutput>#DateFormat(Now())#</cfoutput>).

Examples of Proper and Improper usage of pound signs

Proper Usage

<cfset person = "Paul">
<cfset greeting = "Hello #person#">
<cfoutput>
#greeting#, today is #DateFormat(Now(),"dddd")#.
</cfoutput>

Improper Usage

<!---The improper use is italicized--->
<cfset person = "Paul">
<cfset greeting = "Hello" & #person#>

Improper Usage

<!---The improper use is italicized--->
<cfoutput>
#greeting#, today is #DateFormat(#Now()#,"dddd")#.
</cfoutput>

Arithmetic and String Operators

ColdFusion's arithmetic and string operators are, for the most part, pretty standard.
Operator Type Operator Name Example
Arithmetic + Addition <cfset c = a + b>
- Subtraction <cfset c = a - b>
* Multiplication <cfset c = a * b>
/ Division <cfset c = a / b>
MOD Modulus <cfset c = a MOD b>
^ Exponentiation <cfset c = a^b>
String & Concatenation <cfset greeting = "Hello" & " world!">

#
### ###