Вы находитесь на странице: 1из 338

SYLLABUS (WEB TECHNOLOGY)

UNIT -1
Introduction To Web Design 5

Web page and Web site - Web publishing Process of Web, publishing,
planning, organizing, Hierarchical, Linear, Webbed. Implementing,
Testing, Maintenance.

UNIT -2
HTML 15

 Introduction
 Head section – Prologue, Link, Base, Meta, Script, Style
 Body Section – Header, Paragraphs, Text Formatting, Linking,
Internal Linking, Embedding Images, Lists, Tables, Frames. Other
Special Tags and Characters
 HTML Forms

UNIT -3

Java Script 15

 Introduction
 Language Elements – Identifiers, Expressions, Keywords, Operators,
Statements, Functions
 Object of Java Scripts – Window Object, Document Object, Forms
Objects,
Text Boxes and Text Areas, Buttons, Radio Buttons and Check Boxes,
The
Select Object
 Other Object – The Date Object, The Math Object, The String Object,
Regular Expressions, Arrays, Worked Examples
UNIT -4

DHTML 15

 Introduction
 Cascading Style Sheet (CSS) – Coding, Properties of Text, Property
Values, Other Style Values, In-Line Style Sheet, Embedded Style Sheet,
External Style Sheet, Grouping, Inheritance, Classes as Selector, ID as
Selector, Contextual Selector, Pseudo Classes and Pseudo Elements,
Positioning, Backgrounds, Element Dimensions
 DHTML Document Object Model and Collections – Using the
Collection all, Moving object around the documents
 Event Handling – Assigning Event Handlers, Even Bubbling
 Filters and Transactions
 Data Bindings – Using Tabular Data Control, Sorting Data, Dynamic
Sorting, Filtering

UNIT -5
XML Basics 04

 Introduction
 HTML vs. XML
 Syntax of the XML Document
 XML Attributes

UNIT -6

Publishing the Site 06


 Uploading Web pages - Using FTP and using Web Page Editors
 Web hosting - Shared hosting running a Local Web server
UNIT -1
Introduction To Web Design

Web page and Web site - Web publishing Process of Web,


publishing, planning, organizing, Hierarchical, Linear, Webbed.
Implementing, Testing, Maintenance

(A)Web publishing Process of Web

Web publishing is the process of publishing original content on the


Internet. 
The process includes building and uploading websites, updating the
associated webpages, and posting content to these webpages online.
Web publishing comprises of personal, business, and community
websites in addition to e-books and blogs. 
The content meant for web publishing can include text, videos, digital
images, artwork, and other forms of media. 
Publishers must possess a web server, a web publishing software, and an
Internet connection to carry out web publishing. 
Web publishing is also known as online publishing.
A publisher requires three things to publish content on the Internet: 

 Website development software


 Internet connection
 A web server to host the website
(B)Publishing

The website development software can be a professional web design


application like Dreamweaver or a straightforward web-based content
management system like WordPress. Publishers require an Internet
connection to upload the content to the web server. Major sites may
utilize a dedicated server to host them; however, many smaller websites
usually reside on shared servers that host an array of websites. 

Since web publishing does not demand physical materials like ink and
paper, it costs practically nothing to publish the content. 

Thus, anyone fulfilling the above three requirements can become a web
publisher. In addition, web publishing brings countless visitors as the
published contents are accessed by global visitors. These benefits of web
publishing opened a new era of personal publishing, which was
unimaginable before.

E-book and blog publishers utilize almost the same web publishing tools
used by the website developers. People who do not have the required
web publishing skills seek the services of professional web publishing
individuals or organizations to host, maintain, and modify their websites,
e-books and blogs. 

Posting updates on social media sites like Twitter, Facebook, etc. is


usually not considered web publishing; instead, web publishing usually
refers to uploading original content to unique websites.
(C) Planning

1. Involves the identification of the Web site goals or purpose. The


question to ask is: What is the purpose of this Web site?

2. In addition to understanding the Web site purpose, you should also


ask: Who will use the Website? or knowing the target audience in
terms of: age, gender, computer literacy, etc.

3. Understanding the computing environment will allow the designer


to know what type of Technologies to use.

4. The last question is to ask who will provide the information


included in the Web site.
 
 
(D) Organizing

1. During this phase, the Web designer needs to make decisions about
the Web site content and functionality.

2. It includes a detailed analysis of the content of the Website in


terms information covered, processing required, etc.

3. Websites are designed using any of several different types of


layouts, including linear, hierarchical, and Webbed.

4. Each layout links, or connects, the Web pages in a different


structure to define how users navigate through the site and view
the Web pages.

5. You should select a layout for your Web site based on how users
will most easily navigate through the site to complete tasks and
view the Web site contents.
(E) Hierarchical

A hierarchical Web site layout connects Web pages in a tree-like


structure.  A hierarchical Web site layout works well on a site with a
main index or table of contents page that links to all other Web pages.
With this layout, the main index page would display general information
and secondary pages include information that is more detailed.
 

(F)Linear
 
A linear Web site layout connects Web pages in a straight line.  A
linear Web site layout connects Web pages in a straight line.  A linear
Web is appropriate if the information on the Web pages should be read
in a specific order.
 
 
 
Linear Web Site Layout
 
 
 
 
(G)Webbed Implementing

1. During this phase, the Web designer needs to make decisions about
the Web site content and functionality.

2. It includes a detailed analysis of the content of the Website in


terms information covered, processing required, etc.

A Webbed Web site layout has no set structure. A Webbed Web site


layout works best on Web sites with information that does not need to be
read in a specific order and with many navigation options that users can
select.

Using a combination of the three layouts is appropriate, if it helps users


navigate through the site easily.
 
During the design and development phase, you should also consider
what types of multimedia could contribute positively to the Web site
experience. 
 
Types of multimedia are graphics, photos, video and audio.

 linear, hierarchical and Webbed layouts is used to collect Some of


information on the Web site might be organized hierarchically from an
index page; other information might be accessible from all areas of the
site while other information might be organized linearly to be read in a
specific order.
(H)Testing

A Web site should be tested at various stages of the Web design and
development. This testing should include a review of page content,
functionality and usability.  Some basic steps to test content and
functionality are:
 Reviewing for accurate spelling and proofreading content
including page titles.
 Checking links to ensure that they are not broken and are linked
correctly
 Checking graphics to confirm they display properly and are linked
correctly
 Testing forms and other interactive page elements
 Testing pages to check for speed of loading on lower speed
connection
 Printing each page to check how page s print
 Testing each Web in several different browser types and versions
to verify they display correctly
 
Usability is the measure of how well product, allows users to
accomplish their goals. Usability testing is a method by which users
of a Web site are asked to perform certain tasks in an effort to
measure the ease of use of the product.

(I)Maintenance

Once the Web site testing is complete and any required changes have
been made, the Web site can be implemented.  Implementation of a
Web site means publishing the Web site or uploading it into a Web
server.  
 
Once, the Web site has been implemented, its maintenance will
include updating the information content by removing the outdated
one and putting in the new one.
Periodical checking of the links is also necessary to ensure that they
are still active. 
 
Finally, Website monitoring is another key aspect of maintenance.
Usually, the Web servers that host the Web sites keep logs about Web
site usage.
 
A log is the file that lists all the Web pages that have been requested
from the Web site.
Analyzing the logs allows you to determine the number of visitors to
your site and the browser types and versions they are using, as well as
their connection speeds, most commonly requested pages.

Web Development Phases and Questions


Web development phase Questions to ask
 What is the purpose of the Web
site
 Who will use this Web site
Planning  What are their computing
environment
 Who owns and authors the
information on the Web site
 What information is useful to the
Analysis user
 
 What type of Web site layout is
appropriate
Design and development  What forms of multimedia is
helpful to the user
 
 Is the Web site content correct
 Does the Website functions
correctly
Testing
 Are users able to find the
information they need
 Is the navigation easy to use?
 How is the Web site published
 How is the Web site updated
Implementation and
 Who is responsible for content
Maintenance
updates
 Will the Web site be monitored
 

UNIT -2
HTML

Introduction

 Hyper Text Markup Language (HTML) is the standard markup


language for creating web pages and web applications. With
Cascading Style Sheets (CSS), and JavaScript, it forms a triad of
cornerstone technologies for the World Wide Web.
 Web browsers receive HTML documents from a webserver or
from local storage and render them into multimedia web pages.
HTML describes the structure of a web page semantically and
originally included cues for the appearance of the document.
 HTML elements are the building blocks of HTML pages. With
HTML constructs, images and other objects, such as interactive
forms may be embedded into the rendered page.
 It provides a means to create structured documents by denoting
structural semantics for text such as headings, paragraphs,
lists, links, quotes and other items. HTML elements are delineated
by tags, written using angle brackets.
 Tags such as  <img />  and  <input />  introduce content into the
page directly. Others such as  <p>...</p>  surround and provide
information about document text and may include other tags as
sub-elements. Browsers do not display the HTML tags, but use
them to interpret the content of the page.
 HTML can embed programs written in a scripting language such
as JavaScript which affect the behavior and content of web pages.
Inclusion of CSS defines the look and layout of content.
The World Wide Web Consortium (W3C), maintainer of both the
HTML and the CSS standards, has encouraged the use of CSS over
explicit presentational HTML since 1997.

 Most fundamentally, when you look at a webpage in a Web


browser, you see words. But most of the time webpages
contain styled text rather than plain text.  Nowadays, webpage
designers have access to hundreds of different fonts, font sizes,
colors, and even alphabets (e.g. Spanish, Japanese, Russian), and
browsers can, for the most part, display them accurately.

 Webpages may also contain images, video clips, and background


music. They may include drop-down menus, search boxes, or links
you can follow to access other pages (whether on the same site or
another site).

 Some websites even let visitors customize the page display to


accommodate their preferences and challenges (e.g., sight
challenges, deafness, or color blindness). Often a page contains
content boxes that move (scroll) while the rest of the page remains
static.

 A typical webpage depends on several technologies (such


as CSS, JavaScript, AJAX, JSON) to control what the end-user
sees, but most fundamentally, developers write webpages
in HTML, without which there can be no webpages. To display the
page on the client-side device, a browser starts out by reading the
HTML.
 The W3C (World Wide Web Consortium) and
the WHATWG (Web Hypertext Application Technology Working
Group) maintains the HTML (Hyper Text Markup
Language) international standards and specifications. The
WHATWG treats HTML as a constantly evolving "living
standard", whereas the W3C works both on HTML evolution
(HTML 5.1) and on "snapshots" of HTML (of which the most
recent is HTML5).
 The HTML specification defines a single language that can be
written either with the relaxed HTML syntax or the
stricter XML syntax (Extensible Markup Language). HTML also
addresses the needs of Web apps. HTML only describes the
meaning of the content, not style and formatting. To define
appearance and layout, please use CSS, not explicit
presentational HTML.
History of HTML
1. Tim Berners-Lee, then a contractor at CERN (the European
Organization for Nuclear Research), devised a way in the late
1980s for scientists to share documents over the Internet.
2. Before that, Internet communication had been limited to plain text,
using technologies such as email, FTP (File Transfer Protocol),
and Usenet-based discussion boards. 
3. HTML used a content model stored on a central server but
transferrable to a local workstation and viewable in a browser,
simplifying access to content and making "rich" content possible
(such as sophisticated text formatting and images).
4. HTML is derived from SGML, which is a complex syntax for
marking up or binding of content (text or graphics) in documents;
as of HTML5, HTML no longer attempts to adhere to SGML
syntax.

The basic HTML code structure is shown below:

<html>
<head>
<title>Page title here</title>
</head>
<body>
This is sample text...
<!-- We use this syntax to write comments -->
<!-- Page content and rest of the tags here.... -->
<!-- This is the actual area that gets shown in the browser -->
</body>
</html>
Head section

 The <head> element is a container for metadata (data about data)


and is placed between the <html> tag and the <body> tag.
 HTML metadata is data about the HTML document. Metadata is
not displayed.
 Metadata typically define the document title, character set, styles,
links, scripts, and other meta information.
 The following tags describe metadata: <title>, <style>, <meta>,
<link>, <script>, and <base>

Example
<!DOCTYPE html>
<html>

<head>
  <title>Page Title</title>
</head>

<body>
The content of the document......
</body>

</html>
(A)Prologue

The <!DOCTYPE> declaration represents the document type, and helps


browsers to display web pages correctly.

It must only appear once, at the top of the page (before any HTML tags).

The <!DOCTYPE> declaration is not case sensitive.

The <!DOCTYPE> declaration for HTML is:

<!DOCTYPE html>

(B)Link

The <link> element is used to link to external style sheets:

Example
<link rel="stylesheet" href="mystyle.css">

(C)Base

The <base> element specifies the base URL and base target for all
relative URLs in a page:

Example
<base href="http://www.w3schools.com/images/" target="_blank">
(D)Meta

 The <meta> element is used to specify which character set is used,


page description, keywords, author, and other metadata.

 Metadata is used by browsers (how to display content), by search


engines (keywords), and other web services.

 Define the character set used:

<meta charset="UTF-8">

Define a description of your web page:

<meta name="description" content="Free Web tutorials">

Define keywords for search engines:

<meta name="keywords" content="HTML, CSS, XML, JavaScript">

Define the author of a page:

<meta name="author" content="Hege Refsnes">

Refresh document every 30 seconds:

<meta http-equiv="refresh" content="30">

Example of <meta> tags:

Example
<meta charset="UTF-8">
<meta name="description" content="Free Web tutorials">
<meta name="keywords" content="HTML,CSS,XML,JavaScript">
<meta name="author" content="Hege Refsnes">
(E)Title

The <title> element defines the title of the document, and is required in


all HTML/XHTML documents.

The <title> element:

 defines a title in the browser tab


 provides a title for the page when it is added to favorites
 displays a title for the page in search engine results

A simple HTML document:

Example
<!DOCTYPE html>
<html>
<head>
  <title>Page Title</title>
</head>

<body>
The content of the document......
</body>
</html>
(F)Style

The <style> element is used to define style information for a single


HTML page:

Example
<style>
  body {background-color: powderblue;}
  h1 {color: red;}
  p {color: blue;}
</style>

(F)Script

The <script> element is used to define client-side JavaScripts.This


JavaScript writes "Hello JavaScript!" into an HTML element with
id="demo":
Example
<script>
function myFunction {
    document.getElementById("demo").innerHTML = "Hello
JavaScript!";
}
</script>

HTML head Elements

Tag Description

<head> Defines information about the document

<title> Defines the title of a document

<base> Defines a default address or a default target for all links on a page

<link> Defines the relationship between a document and an external resource

<meta> Defines metadata about an HTML document

<script> Defines a client-side script


Body Section

 The <body> Element
 The <body>...</body> element defines the BODY section of an
HTML document, which encloses the content to be displayed on
the browser's window.
 The <body> tag has the following optional presentation attributes.
All of these presentation attributes are concerned about the
appearance instead of the content, and have been deprecated in
HTML 4 in favor of style sheet.
 However, many older textbooks present them in Chapter 1. Hence,
I shall list them here for completeness. BUT do not use these
attributes. I shall describe how to control the appearance
of<body> using CSS very soon.

 text="color": color of body text.


 bgcolor="color": background color.
 background="url": URL of an image to be used as the background.
 link="color": color of un-visited links.
 vlink="color": color of visited links.
 alink="color": color of active (clicked) links.
For example:
<html>
<body text="blue" bgcolor="lightblue" link="green" vlink="red"
alink="yellow">
<p>Hello</p>
<a href="http://www.google.com">Google</a>
</body>
</html>

The foreground color (of the texts) is "blue", on background color of


"lightblue". You can set different colors for the three types of links via
attributes "link" (for un-visited links), "vlink" (for visited links), and
"alink" (for active link - the "alink" color shows up when you click on
the link).
(A) Header

HTML headings are defined with the <h1> to <h6> tags.

<h1> defines the most important heading. <h6> defines the least
important heading: 

Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>

(B)Paragraphs

HTML paragraphs are defined with the <p> tag:

Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

(C)Text Formatting

Bold Tags
Tag: <b></b>(Has closing tag) </> means closed.
What it Does: Creates bold text
Code Example: <b>this is bold. </b>
What it looks like:
this is bold.

Italic Tags
Tag: <i></i>(Has closing tag) </> means closed.
What it Does: Creates Italic text.
Code Example: <i> This text is italic. </i>
What it looks like:
This text is italic.
Underline Tags
Tag: <u></u>(Has closing tag) </> means closed.
What it Does: Creates bold text
Code Example: <u>this is unerline. </u>
What it looks like:
this is underline.

(D)Linking

HTML links are defined with the <a> tag:

Example
<a href="http://www.w3schools.com">This is a link</a>

The link's destination is specified in the href attribute. 

Attributes are used to provide additional information about HTML


elements.

(E)Internal Linking

<A>...</A>
Often called anchor tags.
Links can be created using the <A>...</A> tags.
Attributes
HREF="..."
where location is the path and filename to the linked file or image
or specifies the email address prefaced with mailto:
l
NAME="..."
each anchor tag can be given a name - this allows you to link directly to
sections where a named
anchor occurs.
A # (hash) symbol is used before the name in the HREF attribute when
linking.
(F)Embedding Images

 Tag: <img src=”imagename.gif” alt=”description”> there is no


closing tag
Attributes:
alt=”description” Align=right or left Border=0
What it does: Inserts an image into the page. Always have an alt tag in
your images. Alt tags are part of priority
one ADA compliance.
 The site will not be compliant without this tag.
Code Example: This is an image <img src=”images/arrow.gif”
alt=”arrow”>.

 What it looks like: This is an image

.
1. Always use alt tags (alternative text) in images
2. Close your tags </>

<IMG>...</IMG>
Images can be included using the <IMG> tag.
SRC="..." - required
specifies the location/source, or URL, of the image
l
HEIGHT="..."
where the image height can be specified in pixels (e.g. 100)
l
l WIDTH="..."
where the image width can be specified in pixels (e.g. 100)
ALT="..."
used to display some alternative text to the image. A good idea as often
people have images switched off to speed up downloading time. Also
important for partially sighted users with text readers.
l
ALIGN=...
specifies the alignment, TOP , MIDDLE , BOTTOM , LEFT , RIGHT
, TEXTTOP ,
ABSMIDDLE , BASELINE or ABSBOTTOM
l
VSPACE="..."
specifies the number of pixels of vertical space left around an image
l
HSPACE="..."
specifies the number of pixels of horizontal space left around an image
l
BORDER="..."
specifies the number of pixels width for the border around the image.
Default is no border, except
of images which are links. Use BORDER="0" to remove borders
l
NAME="..."
assigns a name to the image, mainly for use with JavaScript for mouse
overs.
l
LOWSRC="..."
allows an initial, usually lower resolution, image to be displayed. Final
image is downloaded after
page layout and other LOWSRC images have been loaded.

(G)Lists
An Unordered List:

 Item
 Item
 Item
 Item

An Ordered List:

1. First item
2. Second item
3. Third item
4. Fourth item
Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with
the <li> tag.

The list items will be marked with bullets (small black circles) by
default:

Example

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Unordered HTML List - Choose List Item Marker

The CSS list-style-type property is used to define the style of the list


item marker:

Value Description

disc Sets the list item marker to a bullet (default)

circle Sets the list item marker to a circle

square Sets the list item marker to a square

none The list items will not be marked


Example - Disc
<ul style="list-style-type:disc">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Example - Circle
<ul style="list-style-type:circle">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Example - Square
<ul style="list-style-type:square">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>
Example - None
<ul style="list-style-type:none">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with
the <li> tag.

The list items will be marked with numbers by default:


Example
<ol>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

Ordered HTML List - The Type Attribute

The type attribute of the <ol> tag, defines the type of the list item
marker:

Type Description

type="1" The list items will be numbered with numbers (default)

type="A" The list items will be numbered with uppercase letters

type="a" The list items will be numbered with lowercase letters

type="I" The list items will be numbered with uppercase roman numbers

type="i" The list items will be numbered with lowercase roman numbers

Numbers:

<ol type="1">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
Uppercase Letters:

<ol type="A">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
Lowercase Letters:

<ol type="a">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
Uppercase Roman Numbers:

<ol type="I">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>
Lowercase Roman Numbers:

<ol type="i">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ol>

HTML Description Lists

HTML also supports description lists.


A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list, the <dt> tag defines the term


(name), and the <dd> tag describes each term: 

Example
<dl>
  <dt>Coffee</dt>
  <dd>- black hot drink</dd>
  <dt>Milk</dt>
  <dd>- white cold drink</dd>
</dl>
Nested HTML Lists

List can be nested (lists inside lists):

Example
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul>
      <li>Black tea</li>
      <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>
Note: List items can contain new list, and other HTML elements, like
images and links, etc.

Horizontal Lists

HTML lists can be styled in many different ways with CSS.

One popular way is to style a list horizontally, to create a menu:

Example
<!DOCTYPE html>
<html>
<head>
<style>
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333333;
}

li {
    float: left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111111;
}
</style>
</head>
<body>

<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

</body>
</html>
Chapter Summary

 Use the HTML <ul> element to define an unordered list


 Use the CSS list-style-type property to define the list item marker
 Use the HTML <ol> element to define an ordered list
 Use the HTML type attribute to define the numbering type
 Use the HTML <li> element to define a list item
 Use the HTML <dl> element to define a description list
 Use the HTML <dt> element to define the description term
 Use the HTML <dd> element to describe term term in a
description list
 Lists can be nested inside lists
 List items can contain other HTML elements
 Use the CSS property float:left or display:inline to display a list
horizontally
HTML List Tags

Tag Description

<ul> Defines an unordered list

<ol> Defines an ordered list

<li> Defines a list item

<dl> Defines a description list

<dt> Defines a term in a description list

<dd> Describes the term in a description list


(H)Tables
Defining an HTML Table

An HTML table is defined with the <table> tag.

Each table row is defined with the <tr> tag. A table header is defined


with the <th> tag. By default, table headings are bold and centered. A
table data/cell is defined with the <td> tag.

Example
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

Note: The <td> elements are the data containers of the table.


They can contain all sorts of HTML elements; text, images, lists, other
tables, etc.
HTML Table - Adding a Border

If you do not specify a border for the table, it will be displayed without
borders.A border is set using the CSS border property:

Example
table, th, td {
    border: 1px solid black;
}

Remember to define borders for both the table and the table cells.

HTML Table - Collapsed Borders

If you want the borders to collapse into one border, add the CSS border-
collapse property:

Example
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
HTML Table - Adding Cell Padding

Cell padding specifies the space between the cell content and its borders.

If you do not specify a padding, the table cells will be displayed without
padding.

To set the padding, use the CSS padding property:

Example
th, td {
    padding: 15px;
}
HTML Table - Left-align Headings

By default, table headings are bold and centered.

To left-align the table headings, use the CSS text-align property:

Example
th {
    text-align: left;
}
HTML Table - Adding Border Spacing

Border spacing specifies the space between the cells.To set the border
spacing for a table, use the CSS border-spacing property:

Example
table {
    border-spacing: 5px;
}

Note: If the table has collapsed borders, border-spacing has no effect.

HTML Table - Cells that Span Many Columns

To make a cell span more than one column, use the colspan attribute:

Example
<table style="width:100%">
  <tr>
    <th>Name</th>
    <th colspan="2">Telephone</th>
  </tr>
  <tr>
    <td>Bill Gates</td>
    <td>55577854</td>
    <td>55577855</td>
  </tr>
</table>
HTML Table - Cells that Span Many Rows

To make a cell span more than one row, use the rowspan attribute:


Example

<table style="width:100%">
  <tr>
    <th>Name:</th>
    <td>Bill Gates</td>
  </tr>
  <tr>
    <th rowspan="2">Telephone:</th>
    <td>55577854</td>
  </tr>
  <tr>
    <td>55577855</td>
  </tr>
</table>
HTML Table - Adding a Caption
To add a caption to a table, use the <caption> tag:
Example
<table style="width:100%">
  <caption>Monthly savings</caption>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td> Note: The
    <td>$100</td> <caption> tag must
  </tr> be inserted
  <tr> immediately after
the <table> tag.
    <td>February</td>
    <td>$50</td></tr></table>
  A Special Style for One Table
To define a special style for a special table, add an id attribute to the
table:
Example
<table id="t01">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>
Now you can define a special style for this table:
table#t01 {
    width: 100%; 
    background-color: #f1f1c1;
}
And add more styles:
table#t01 tr:nth-child(even) {
    background-color: #eee;
}
table#t01 tr:nth-child(odd) {
    background-color: #fff;
}
table#t01 th {
    color: white;
    background-color: black;
}
Chapter Summary

 Use the HTML <table> element to define a table


 Use the HTML <tr> element to define a table row
 Use the HTML <td> element to define a table data
 Use the HTML <th> element to define a table heading
 Use the HTML <caption> element to define a table caption
 Use the CSS border property to define a border
 Use the CSS border-collapse property to collapse cell borders
 Use the CSS padding property to add padding to cells
 Use the CSS text-align property to align cell text
 Use the CSS border-spacing property to set the spacing between
cells
 Use the colspan attribute to make a cell span many columns
 Use the rowspan attribute to make a cell span many rows
 Use the id attribute to uniquely define one table

HTML Table Tags

Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

<td> Defines a cell in a table

<caption> Defines a table caption


<colgroup> Specifies a group of one or more columns in a table for

formatting

<col> Specifies column properties for each column within a <colgroup>

element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

(I)Frames
HTML frames are used to divide your browser window into multiple
sections where each section can load a separate HTML document. A
collection of frames in the browser window is known as a frameset. The
window is divided into frames in a similar way the tables are organized:
into rows and columns.
Disadvantages of Frames
There are few drawbacks with using frames, so it's never recommended
to use frames in your webpages:

 Some smaller devices cannot cope with frames often because their
screen is not big enough to be divided up.
 Sometimes your page will be displayed differently on different
computers due to different screen resolution.
 The browser's back button might not work as the user hopes.
 There are still few browsers that do not support frame technology.
Creating Frames
To use frames on a page we use <frameset> tag instead of <body> tag.
The <frameset> tag defines how to divide the window into frames.
The rowsattribute of <frameset> tag defines horizontal frames
and cols attribute defines vertical frames. Each frame is indicated by
<frame> tag and it defines which HTML document shall open into the
frame.
Example
Following is the example to create three horizontal frames:

<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows="10%,80%,10%">
<frame name="top" src="/html/top_frame.htm" />
<frame name="main" src="/html/main_frame.htm" />
<frame name="bottom" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
This will produce following result:

Example
Let's put above example as follows, here we replaced rows attribute by
cols and changed their width. This will create all the three frames
vertically:

<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset cols="25%,50%,25%">
<frame name="left" src="/html/top_frame.htm" />
<frame name="center" src="/html/main_frame.htm" />
<frame name="right" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
This will produce following result:

The <frameset> Tag Attributes


Following are important attributes of the <frameset> tag:

Attribute Description

cols specifies how many columns are contained in the


frameset and the size of each column. You can
specify the width of each column in one of four
ways:

 Absolute values in pixels. For example to


create three vertical frames, use cols="100,
500,100".
 A percentage of the browser window. For
example to create three vertical frames,
use cols="10%, 80%,10%".
 Using a wildcard symbol. For example to
create three vertical frames, use cols="10%,
*,10%". In this case wildcard takes remainder
of the window.
 As relative widths of the browser window. For
example to create three vertical frames,
use cols="3*,2*,1*". This is an alternative to
percentages. You can use relative widths of
the browser window. Here the window is
divided into sixths: the first column takes up
half of the window, the second takes one third,
and the third takes one sixth.

rows This attribute works just like the cols attribute and
takes the same values, but it is used to specify the
rows in the frameset. For example to create two
horizontal frames, use rows="10%, 90%". You can
specify the height of each row in the same way as
explained above for columns.
border This attribute specifies the width of the border of
each frame in pixels. For example border="5". A
value of zero means no border.
frameborder This attribute specifies whether a three-dimensional
border should be displayed between frames. This
attrubute takes value either 1 (yes) or 0 (no). For
example frameborder="0" specifies no border.
framespacin This attribute specifies the amount of space between
g frames in a frameset. This can take any integer value.
For example framespacing="10" means there should
be 10 pixels spacing between each frames.
Following are important attributes of <frame> tag:

Attribute Description

src This attribute is used to give the file name that


should be loaded in the frame. Its value can be any
URL. For example, src="/html/top_frame.htm" will
load an HTML file available in html directory.

name This attribute allows you to give a name to a frame.


It is used to indicate which frame a document should
be loaded into. This is especially important when you
want to create links in one frame that load pages into
an another frame, in which case the second frame
needs a name to identify itself as the target of the
link.

frameborder This attribute specifies whether or not the borders of


that frame are shown; it overrides the value given in
the frameborder attribute on the <frameset> tag if
one is given, and this can take values either 1 (yes) or
0 (no).

marginwidth This attribute allows you to specify the width of the


space between the left and right of the frame's
borders and the frame's content. The value is given in
pixels. For example marginwidth="10".

marginheight This attribute allows you to specify the height of the


space between the top and bottom of the frame's
borders and its contents. The value is given in pixels.
For example marginheight="10".

noresize By default you can resize any frame by clicking and


dragging on the borders of a frame. The noresize
attribute prevents a user from being able to resize the
frame. For example noresize="noresize".

scrolling This attribute controls the appearance of the


scrollbars that appear on the frame. This takes values
either "yes", "no" or "auto". For example
scrolling="no" means it should not have scroll bars.

longdesc This attribute allows you to provide a link to another


page containing a long description of the contents of
the frame. For example
longdesc="framedescription.htm"

Target attribute of frame

Option Description

_self Loads the page into the current frame.

_blank Loads a page into a new browser window.opening a


new window.

_parent Loads the page into the parent window, which in the
case of a single frameset is the main browser window.

_top Loads the page into the browser window, replacing


any current frames.

targetframe Loads the page into a named targetframe.


(J) Other Special Tags and Characters

If you need a to use a special character, like an accented character or a


currency sign, you have to use a special notation. There are two ways to
use these special characters:

1. Use the decimal representation, in the format &#nnn;, where nnn is


the decimal code of the character.
2. Use a character entity, in the format &ccc;, where ccc is the
character string that represents the specific character.

HTML 4.0 supports three sets of special characters:

 ISO 8859-1 (Latin-1) characters


 Symbols, mathematical symbols, and Greek letters
 Markup-significant and internationalization characters

ISO 8859-1 (Latin-1) characters


ISO 8859-1 (Latin-1) characters
Decima
Character Example Explanation
l
&#160; &nbsp;   no-break space
&#161; &iexcl; ¡ inverted exclamation mark
&#162; &cent; ¢ cent sign
&#163; &pound; £ pound sign
&#164; &curren; ¤ currency sign
&#165; &yen; ¥ yen sign = yuan sign
&#166; &brvbar; ¦ broken bar = brolen vertical bar
&#167; &sect; § section sign
&#168; &uml; ¨ diaeresis = spacing diaeresis
&#169; &copy; © copyright sign
&#170; &ordf; ª feminine ordinal indicator
left-pointing double angle quotation mark
&#171; &laquo; «
= left pointing guillemet
&#172; &not; ¬ not sign = discretionary hyphen
&#173; &shy; soft hyphen = discretionary hyphen
registered sign = registered trade mark
&#174; &reg; ®
sign
macron = spacing macron = overline =
&#175; &macr; ¯
APL overbar
&#176; &deg; ° degree sign
&#177; &plusmn; ± plus-minus sign = plus-or-minus sign
superscript two = superscript digit two =
&#178; &sup2; ²
squared
superscript three = superscript digit three
&#179; &sup3; ³
= cubed
&#180; &acute; ´ acute accent = spacing acute
&#181; &micro; µ micro sign
&#182; &para; ¶ pilcrow sign = paragraph sign
middle dot = Georgian comma = Greek
&#183; &middot; ·
middle dot
&#184; &ccedil; ¸ cedilla = spacing cedilla
&#185; &sup1; ¹ superscript one = superscript digit one
&#186; &ordm; º masculine ordinal indicator
right-pointing double angle quotation
&#187; &raquo; »
mark = right pointing guillemet
&#188; &frac14; ¼ vulgar fraction one quarter = fraction one
quarter
&#189; &frac12; ½ vulgar fraction one half = fraction one half
vulgar fraction three quarters = fraction
&#190; &frac34; ¾
three quarters
inverted question mark = turned question
&#191; &iquest; ¿
mark
latin capital letter A with grave = latin
&#192; &Agrave; À
capital letter A grave
&#193; &Aacute; Á latin capital letter A with acute
&#194; &Acirc; Â latin capital letter A with circumflex
&#195; &Atilde; Ã latin capital letter A with tilde
&#196; &Auml; Ä latin capital letter A with diaeresis
latin capital letter A with ring above =
&#197; &Aring; Å
latin capital letter A ring
latin capital letter AE = latin capital
&#198; &AElig; Æ
ligature AE
&#199; &Ccedil; Ç latin capital letter C with cedilla
&#200; &Egrave; È latin capital letter E with grave
&#201; &Eacute; É latin capital letter E with acute
&#202; &Ecirc; Ê latin capital letter E with circumflex
&#203; &Euml; Ë latin capital letter E with diaeresis
&#204; &Igrave; Ì latin capital letter I with grave
&#205; &Iacute; Í latin capital letter I with acute
&#206; &Icirc; Î latin capital letter I with circumflex
&#207; &Iuml; Ï latin capital letter I with diaeresis
&#208; &ETH; Ð latin capital letter ETH
&#209; &Ntilde; Ñ latin capital letter N with tilde
&#210; &Ograve; Ò latin capital letter O with grave
&#211; &Oacute; Ó latin capital letter O with acute
&#212; &Ocirc; Ô latin capital letter O with circumflex
&#213; &Otilde; Õ latin capital letter O with tilde
&#214; &Ouml; Ö latin capital letter O with diaeresis
&#215; &times; × multiplication sign
latin capital letter O with stroke = latin
&#216; &Oslash; Ø
capital letter O slash
&#217; &Ugrave; Ù latin capital letter U with grave
&#218; &Uacute; Ú latin capital letter U with acute
&#219; &Ucirc; Û latin capital letter U with circumflex
&#220; &Uuml; Ü latin capital letter U with diaeresis
&#221; &Yacute; Ý latin capital letter Y with acute
&THORN
&#222; Þ latin capital letter THORN
;
&#223; &szlig; ß latin small letter sharp s = ess-zed
latin small letter a with grave = latin small
&#224; &agrave; à
letter a grave
&#225; &aacute; á latin small letter a with acute
&#226; &acirc; â latin small letter a with circumflex
&#227; &atilde; ã latin small letter a with tilde
&#228; &auml; ä latin small letter a with diaeresis
latin small letter a with ring above = latin
&#229; &aring; å
small letter a ring
&#230; &aelig; æ latin small letter ae = latin small ligature
ae
&#231; &ccedil; ç latin small letter c with cedilla
&#232; &egrave; è latin small letter e with grave
&#233; &eacute; é latin small letter e with acute
&#234; &ecirc; ê latin small letter e with circumflex
&#235; &euml; ë latin small letter e with diaeresis
&#236; &igrave; ì latin small letter i with grave
&#237; &iacute; í latin small letter i with acute
&#238; &icirc; î latin small letter i with circumflex
&#239; &iuml; ï latin small letter i with diaeresis
&#240; &eth; ð latin small letter eth
&#241; &ntilde; ñ latin small letter n with tilde
&#242; &ograve; ò latin small letter o with grave
&#243; &oacute; ó latin small letter o with acute
&#244; &ocirc; ô latin small letter o with circumflex
&#245; &otilde; õ latin small letter o with tilde
&#246; &ouml; ö latin small letter o with diaeresis
&#247; &divide; ÷ division sign
latin small letter o with stroke = latin
&#248; &oslash; ø
small letter o slash
&#249; &ugrave; ù latin small letter u with grave
&#250; &uacute; ú latin small letter u with acute
&#251; &ucirc; û latin small letter u with circumflex
&#252; &uuml; ü latin small letter u with diaeresis
&#253; &yacute; ý latin small letter y with acute
&#254; &thorn; þ latin small letter thorn with
&#255; &yuml; ÿ latin small letter y with diaeresis

Symbols, mathematical symbols, and Greek letters


The character entity references in this section produce characters that
may be represented by glyphs in the widely available Adobe Symbol
font, including Greek characters, various bracketing symbols, and a
selection of mathematical operators such as gradient, product, and
summation symbols.

Note from HTML 4.0 :

This entity set contains all the letters used in modern Greek. However, it
does not include Greek punctuation, precomposed accented characters
nor the non-spacing accents (tonos, dialytika) required to compose them.
There are no archaic letters, Coptic-unique letters, or precomposed
letters for Polytonic Greek. The entities defined here are not intended for
the representation of modern Greek text and would not be an efficient
representation; rather, they are intended for occasional Greek letters
used in technical and mathematical works.

Symbols, mathematical symbols, and Greek letters


Decimal Character Example Explanation
&#402; &fnof; ƒ latin small f with hook = function =
florin
&#913; &Alpha; Α greek capital letter alpha
&#914; &Beta; Β greek capital letter beta
&#915; &Gamma; Γ greek capital letter gamma
&#916; &Delta; Δ greek capital letter delta
&#917; &Epsilon; Ε greek capital letter epsilon
&#918; &Zeta; Ζ greek capital letter zeta
&#919; &Eta; Η greek capital letter eta
&#920; &Theta; Θ greek capital letter theta
&#921; &Iota; Ι greek capital letter iota
&#922; &Kappa; Κ greek capital letter kappa
&#923; &Lambda; Λ greek capital letter lambda
&#924; &Mu; Μ greek capital letter mu
&#925; &Nu; Ν greek capital letter nu
&#926; &Xi; Ξ greek capital letter xi
&#927; &Omicron; Ο greek capital letter omicron
&#928; &Pi; Π greek capital letter pi
&#929; &Rho; Ρ greek capital letter rho
&#931; &Sigma; Σ greek capital letter sigma
&#932; &Tau; Τ greek capital letter tau
&#933; &Upsilon; Υ greek capital letter upsilon
&#934; &Phi; Φ greek capital letter phi
&#935; &Chi; Χ greek capital letter chi
&#936; &Psi; Ψ greek capital letter psi
&#937; &Omega; Ω greek capital letter omega
&#945; &alpha; α greek small letter alpha
&#946; &beta; β greek small letter beta
&#947; &gamma; γ greek small letter gamma
&#948; &delta; δ greek small letter delta
&#949; &epsilon; ε greek small letter epsilon
&#950; &zeta; ζ greek small letter zeta
&#951; &eta; η greek small letter eta
&#952; &theta; θ greek small letter theta
&#953; &iota; ι greek small letter iota
&#954; &kappa; κ greek small letter kappa
&#955; &lambda; λ greek small letter lambda
&#956; &mu; μ greek small letter mu
&#957; &nu; ν greek small letter nu
&#958; &xi; ξ greek small letter xi
&#959; &omicron; ο greek small letter omicron
&#960; &pi; π greek small letter pi
&#961; &rho; ρ greek small letter rho
&#962; &sigmaf; ς greek small letter final sigma
&#963; &sigma; σ greek small letter sigma
&#964; &tau; τ greek small letter tau
&#965; &upsilon; υ greek small letter upsilon
&#966; &phi; φ greek small letter phi
&#967; &chi; χ greek small letter chi
&#968; &psi; ψ greek small letter psi
&#969; &omega; ω greek small letter omega
&#977; &thetasym; ϑ greek small letter theta symbol
&#978; &upsih; ϒ greek upsilon with hook symbol
&#982; &piv; ϖ greek pi symbol
&#8226 &bull; • bullet = black small circle
;
&#8230 &hellip; … horizontal ellipsis = three dot leader
;
&#8242 &prime; ′ prime = minutes = feet
;
&#8243 &Prime; ″ double prime = seconds = inches
;
&#8254 &oline; ‾ overline = spacing overscore
;
&#8260 &frasl; ⁄ fraction slash
;
&#8472 &weierp; ℘ script capital P = power set =
; Weierstrass p
&#8465 &image; ℑ blackletter capital I = imaginary part
;
&#8476 &real; ℜ blackletter capital R = real part
; symbol
&#8482 &trade; ™ trade mark sign
;
&#8501 &alefsym; ℵ alef symbol = first transfinite cardinal
;
&#8592 &larr; ← leftwards arrow
;
&#8593 &uarr; ↑ upwards arrow
;
&#8594 &rarr; → rightwards arrow
;
&#8595 &darr; ↓ downwards arrow
;
&#8596 &harr; ↔ left right arrow
;
&#8629 &crarr; ↵ downwards arrow with corner
; leftwards = carriage return
&#8656 &lArr; ⇐ leftwards double arrow
;
&#8657 &uArr; ⇑ upwards double arrow
;
&#8658 &rArr; ⇒ rightwards double arrow
;
&#8659 &dArr; ⇓ downwards double arrow
;
&#8660 &hArr; ⇔ left right double arrow
;
&#8704 &forall; ∀ for all
;
&#8706 &part; ∂ partial differential
;
&#8707 &exist; ∃ there exists
;
&#8709 &empty; ∅ empty set = null set = diameter
;
&#8711 &nabla; ∇ nabla = backward difference
;
&#8712 &isin; ∈ element of
;
&#8713 &notin; ∉ not an element of
;
&#8715 &ni; ∋ contains as member
;
&#8719 &prod; ∏ n-ary product = product sign
;
&#8721 &sum; ∑ n-ary sumation
;
&#8722 &minus; − minus sign
;
&#8727 &lowast; ∗ asterisk operator
;
&#8730 &radic; √ square root = radical sign
;
&#8733 &prop; ∝ proportional to
;
&#8734 &infin; ∞ infinity
;
&#8736 &ang; ∠ angle
;
&#8743 &and; ∧ logical and = wedge
;
&#8744 &or; ∨ logical or = vee
;
&#8745 &cap; ∩ intersection = cap
;
&#8746 &cup; ∪ union = cup
;
&#8747 &int; ∫ integral
;
&#8756 &there4; ∴ therefore
;
&#8764 &sim; ∼ tilde operator = varies with = similar
; to
&#8773 &cong; ≅ approximately equal to
;
&#8776 &asymp; ≈ almost equal to = asymptotic to
;
&#8800 &ne; ≠ not equal to
;
&#8801 &equiv; ≡ identical to
;
&#8804 &le; ≤ less-than or equal to
;
&#8805 &ge; ≥ greater-than or equal to
;
&#8834 &sub; ⊂ subset of
;
&#8835 &sup; ⊃ superset of
;
&#8836 &nsub; ⊄ not a subset of
;
&#8838 &sube; ⊆ subset of or equal to
;
&#8839 &supe; ⊇ superset of or equal to
;
&#8853 &oplus; ⊕ circled plus = direct sum
;
&#8855 &otimes; ⊗ circled times = vector product
;
&#8869 &perp; ⊥ up tack = orthogonal to =
; perpendicular
&#8901 &sdot; ⋅ dot operator
;
&#8968 &lceil; ⌈ left ceiling = apl upstile
;
&#8969 &rceil; ⌉ right ceiling
;
&#8970 &lfloor; ⌊ left floor = apl downstile
;
&#8971 &rfloor; ⌋ right floor
;
&#9001 &lang; 〈 left-pointing angle bracket = bra
;
&#9002 &rang; 〉 right-pointing angle bracket = ket
;
&#9674 &loz; ◊ lozenge
;
&#9824 &spades; ♠ black spade suit
;
&#9827 &clubs; ♣ black club suit = shamrock
;
&#9829 &hearts; ♥ black heart suit = valentine
;
&#9830 &diams; ♦ black diamond suit
;
Markup-significant and internationalization characters
The character entity references in this section are for escaping markup-
significant characters, for denoting spaces and dashes. Other characters
in this section apply to internationalization issues such as the
disambiguation of bidirectional text.
Markup-significant and internationalization characters
Decimal Characte Example Explanation
r
&#34; &quot; " quotation mark = APL quote
&#38; &amp; & ampersand
&#60; &lt; < less-than sign
&#62; &gt; > greater-than sign
&#338; &OElig; Πlatin capital ligature OE
&#339; &oelig; œ latin small ligature oe
&#352; &Scaron; Š latin capital letter S with caron
&#353; &scaron; š latin small letter s with caron
&#376; &Yuml; Ÿ latin capital letter Y with diaeresis
&#710; &circ; ˆ modifier letter circumflex accent
&#732; &tilde; ˜ small tilde
&#8194 &ensp;   en space
;
&#8195 &emsp;   em space
;
&#8201 &thinsp;   thin space
;
&#8204 &zwnj; ‌ zero width non-joiner
;
&#8205 &zwj; ‍ zero width joiner
;
&#8206 &lrm; left-to-right mark
;
&#8207 &rlm; right-to-left mark
;
&#8211 &ndash; – en dash
;
&#8212 &mdash; — em dash
;
&#8216 &lsquo; ‘ left single quotation mark
;
&#8217 &rsquo; ’ right single quotation mark
;
&#8218 &sbquo; ‚ single low-9 quotation mark
;
&#8220 &ldquo; “ left double quotation mark
;
&#8221 &rdquo; ” right double quotation mark
;
&#8222 &bdquo; „ double low-9 quotation mark
;
&#8224 &dagger; † dagger
;
&#8225 &Dagger; ‡ double dagger
;
&#8240 &permil; ‰ per mille sign
;
&#8249 &lsaquo; ‹ single left-pointing angle quotation
; mark
&#8250 &rsaquo; › single right-pointing angle quotation
; mark
&#8364 &euro; € euro sign
;
HTML Forms

The HTML <form> element defines a form that is used to collect user


input:

<form>
.
form elements
.
</form>

An HTML form contains form elements.

Form elements are different types of input elements, like text fields,
checkboxes, radio buttons, submit buttons, and more.

The <input> Element

The <input> element is the most important form element.

The <input> element can be displayed in several ways, depending on


the type attribute.

Here are some examples:

Type Description

<input type="text"> Defines a one-line text input field

<input type="radio"> Defines a radio button (for selecting one of many ch

<input type="submit"> Defines a submit button (for submitting the form)


Text Input

<input type="text"> defines a one-line input field for text input:

Example
<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname">
</form>

This is how it will look like in a browser:

First name:

Last name:

Note: The form itself is not visible. Also note that the default width of a
text field is 20 characters.

Radio Button Input

<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices:

Example
<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
</form>

 Male
 Female
 Other
The Submit Button

<input type="submit"> defines a button for submitting the form data


to a form-handler.
The form-handler is typically a server page with a script for processing
input data.
The form-handler is specified in the form's action attribute:

Example
<form action="action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>

This is how the HTML code above will be displayed in a browser:

First name:
Mickey
 
Last name:
Mouse
 

Submit

The Action Attribute

The action attribute defines the action to be performed when the form is


submitted.
Normally, the form data is sent to a web page on the server when the
user clicks on the submit button.
In the example above, the form data is sent to a page on the server called
"action_page.php". This page contains a server-side script that handles
the form data:

<form action="action_page.php">

If the action attribute is omitted, the action is set to the current page.
The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be


used when submitting the form data:

<form action="action_page.php" method="get">

or:

<form action="action_page.php" method="post">

When to Use GET?

The default method when submitting form data is GET.

However, when GET is used, the submitted form data will be visible in
the page address field:

action_page.php?firstname=Mickey&lastname=Mouse

Note: GET must NOT be used when sending sensitive information!


GET is best suited for short, non-sensitive, amounts of data, because it
has size limitations too.

When to Use POST?

Always use POST if the form data contains sensitive or personal


information. The POST method does not display the submitted form data
in the page address field.

POST has no size limitations, and can be used to send large amounts of
data.
The Name Attribute

Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that input field will not be
sent at all.

This example will only submit the "Last name" input field:

Example
<form action="action_page.php">
  First name:<br>
  <input type="text" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>
Grouping Form Data with <fieldset>

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

Example
<form action="action_page.php">
  <fieldset>
    <legend>Personal information:</legend>
    First name:<br>
    <input type="text" name="firstname" value="Mickey"><br>
    Last name:<br>
    <input type="text" name="lastname" value="Mouse"><br><br>
    <input type="submit" value="Submit">
  </fieldset>
</form>

This is how the HTML code above will be displayed in a browser:


Personal information: First name:
Mickey
 
Last name:
Mouse
 

Submit

Here is the list of <form> attributes:

Attribute Description

accept-charset Specifies the charset used in the submitted form (default: the

page charset).

action Specifies an address (url) where to submit the form

(default: the submitting page).

autocomplete Specifies if the browser should autocomplete the form

(default: on).

enctype Specifies the encoding of the submitted data

(default: is url-encoded).

method Specifies the HTTP method used when submitting the form
(default: GET).

name Specifies a name used to identify the form

(for DOM usage: document.forms.name).

novalidate Specifies that the browser should not validate the form.

target Specifies the target of the address in the action attribute

(default: _self).
UNIT -3

Java Script

Introduction
 One of many JavaScript HTML methods is getElementById().

 This example uses the method to "find" an HTML element (with


id="demo") and changes the element content (innerHTML) to "Hello
JavaScript":

Example
document.getElementById("demo").innerHTML = "Hello JavaScript";

<!DOCTYPE html>

<html>

<body>

<h1>What Can JavaScript Do?</h1>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick="document.getElementById('demo').innerHTML


= 'Hello JavaScript!'">Click Me!</button>

</body>

</html>

 What Can JavaScript Do?

JavaScript can change HTML content.


JavaScript Can Change HTML Attributes
This example changes an HTML image by changing the src (source) attribute of
an <img> tag:

The Light Bulb

Turn on the light   Turn off the light

JavaScript Can Change HTML Styles (CSS)

Changing the style of an HTML element, is a variant of changing an


HTML attribute:

Example
document.getElementById("demo").style.fontSize = "25px";
JavaScript Can Hide HTML Elements

Hiding HTML elements can be done by changing the display style:

Example
document.getElementById("demo").style.display="none";
JavaScript Can Show HTML Elements

Showing hidden HTML elements can also be done by changing the


display style:

Example
document.getElementById("demo").style.display="block";
Language Elements

(A)Identifiers

 An identifier is simply a name. In JavaScript, identifiers are used


to name variables and functions and to provide labels for certain
loops in JavaScript code.

 The rules for legal identifier names are the same in JavaScript as
they are in Java and many other languages. The first character must
be a letter, anunderscore (_), or a dollar sign ($).

  Subsequent characters may be any letter or digit or an underscore


or dollar sign. (Numbers are not allowed as the first character so
that JavaScript can easily distinguish identifiers from numbers.)
These are all legal identifiers:

 Note that dollar signs are not legal in identifiers prior to JavaScript
1.1. They are intended for use only by code-generation tools, so
you should avoid using dollar signs in identifiers in the code you
write yourself.

i
my_variable_name
v13
_dummy
$str

 JavaScript programs that contain Unicode characters into a form


that allows them to be manipulated with text editors and other tools
that do not support the full Unicode character set.

 Finally, identifiers cannot be the same as any of the keywords used


for other purposes in JavaScript. The next section lists the special
names that are reserved in JavaScript.
(B)Expressions

 An expression is any valid unit of code that resolves to a value.


Every syntactically valid expression resolves to some value but
conceptually, there are two types of expressions: with side effects (for
example: those that assign value to a variable) and those that in some
sense evaluates and therefore resolves to value.

 The expression x = 7 is an example of the first type. This


expression uses the = operator to assign the value seven to the
variable x. The expression itself evaluates to seven.
 The code 3 + 4 is an example of the second expression type. This
expression uses the + operator to add three and four together
without assigning the result, seven, to a variable.

JavaScript has the following expression categories:

 Arithmetic: evaluates to a number, for example 3.14159.


(Generally uses arithmetic operators.)
 String: evaluates to a character string, for example, "Fred" or
"234". (Generally usesstring operators.)
 Logical: evaluates to true or false. (Often involves logical
operators.)
 Primary expressions: Basic keywords and general expressions in
JavaScript.
 Left-hand-side expressions: Left values are the destination of an
assignment.
(C) Keywords

Basic keywords and general expressions in JavaScript.

this
 Use the this keyword to refer to the current object. In
general, this refers to the calling object in a method. Use this either
with the dot or the bracket notation:
this["propertyName"]

this.propertyName

 Suppose a function called validate validates an


object's value property, given the object and the high and low
values:
function validate(obj, lowval, hival){
if ((obj.value < lowval) || (obj.value > hival))
console.log("Invalid Value!");
}
You could call validate in each form element's onChange event handler,
using this to pass it the form element, as in the following example:
<p>Enter a number between 18 and 99:</p>
<input type="text" name="age" size=3 onChange="validate(this, 18,
99);">

New keyword
You can use the new operator to create an instance of a user-defined
object type or of one of the built-in object types. Use new as follows:
var objectName = new objectType([param1, param2, ..., paramN]);

Super Keyword
The super keyword is used to call functions on an object's parent. It is
useful with classes to call the parent constructor, for example.
super([arguments]); // calls the parent constructor.

super.functionOnParent([arguments]);
(D)Operators

JavaScript has the following types of operators. This section describes


the operators and contains information about operator precedence.

 Assignment operators
 Comparison operators
 Arithmetic operators
 Bitwise operators
 Logical operators
 String operators
 Conditional (ternary) operator
 Comma operator
 Unary operators
 Relational operator

Name Shorthand operator Meaning

Assignment x=y x=y

Addition
x += y x=x+y
assignment

Subtraction
x -= y x=x-y
assignment

Multiplication
x *= y x=x*y
assignment

Division
x /= y x=x/y
assignment

Remainder x %= y x = x % y


Name Shorthand operator Meaning

assignment

Exponentiation
x **= y x = x ** y
assignment

Left shift
x <<= y x = x << y
assignment

Right shift
x >>= y x = x >> y
assignment

Unsigned right
x >>>= y x = x >>> y
shift assignment

Bitwise AND
x &= y x=x&y
assignment

Bitwise XOR
x ^= y x=x^y
assignment

Bitwise OR
x |= y x=x|y
assignment

Comparison operators
A comparison operator compares its operands and returns a logical value
based on whether the comparison is true. The operands can be
numerical, string, logical, or object values.

Examples
Operator Description returning
true

Equal (==) Returns true if the operands are equal. 3 == var1


Name Shorthand operator Meaning

"3" == var1
3 == '3'

Returns true if the operands are not var1 != 4


Not equal (!=)
equal. var2 != "3"

Returns true if the operands are equal


Strict equal(===) and of the same type. See 3 === var1
also Object.is and sameness in JS.

Returns true if the operands are of the


Strict not equal (! var1 !== "3"
same type but not equal, or are of
==) 3 !== '3'
different type.

Returns true if the left operand is var2 > var1


Greater than(>)
greater than the right operand. "12" > 2

Returns true if the left operand is var2 >=


Greater than or
greater than or equal to the right var1
equal (>=)
operand. var1 >= 3

Returns true if the left operand is less var1 < var2


Less than (<)
than the right operand. "2" < 12

var1 <=
Less than or Returns true if the left operand is less
var2
equal (<=) than or equal to the right operand.
var2 <= 5

Arithmetic operator

An arithmetic operator takes numerical values (either literals or


variables) as their operands and returns a single numerical value. The
standard arithmetic operators are addition (+), subtraction (-),
multiplication (*), and division (/).
Operator Description Example

Remainder (%) Binary operator. Returns the 12 % 5 returns 2.


integer remainder of dividing
the two operands.

Increment (++) Unary operator. Adds one to If x is 3, then +


its operand. If used as a +x setsx to 4 and
prefix operator (++x), returns returns 4, whereas x+
the value of its operand after + returns 3 and, only
adding one; if used as a then, setsx to 4.
postfix operator (x++),
returns the value of its
operand before adding one.

Decrement (--) Unary operator. Subtracts one If x is 3, then --


from its operand. The return x setsx to 2 and returns
value is analogous to that for 2, whereas x-- returns 3
the increment operator. and, only then, setsx to
2.

Unary Unary operator. Returns the If x is 3, then -xreturns


negation (-) negation of its operand. -3.

Unary plus (+) Unary operator. Attempts to +"3" returns 3.


convert the operand to a +true returns 1.
number, if it is not already.

Exponentiation Calculates the base to 2 ** 3 returns 8.


operator (**)  the exponent power, that 10 ** -1 returns0.1.
is,baseexponent
Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and
ones), rather than as decimal, hexadecimal, or octal numbers. For
example, the decimal number nine has a binary representation of 1001.
Bitwise operators perform their operations on such binary
representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.

Operator Usage Description

Returns a one in each bit position for


Bitwise AND a&b which the corresponding bits of both
operands are ones.

Returns a zero in each bit position for


Bitwise OR a|b which the corresponding bits of both
operands are zeros.

Returns a zero in each bit position for


which the corresponding bits are the same.
Bitwise XOR a^b
[Returns a one in each bit position for
which the corresponding bits are different.]

Bitwise NOT ~a Inverts the bits of its operand.

Shifts a in binary representation b bits to


Left shift a << b
the left, shifting in zeros from the right.

Sign-propagating Shifts a in binary representation b bits to


a >> b
right shift the right, discarding bits shifted off.

Shifts a in binary representation b bits to


Zero-fill right a >>>
the right, discarding bits shifted off, and
shift b
shifting left.
Logical operators
Logical operators are typically used with Boolean (logical) values;
when they are, they return a Boolean value. However,
the && and || operators actually return the value of one of the specified
operands, so if these operators are used with non-Boolean values, they
may return a non-Boolean value.

Operator Usage Description

Logical expr1 Returns expr1 if it can be converted to false;


AND(&&) && otherwise, returns expr2. Thus, when used with
expr2 Boolean values, && returns true if both operands
are true; otherwise, returns false.

Logical expr1 || Returns expr1 if it can be converted to true;


OR (||) expr2 otherwise, returns expr2. Thus, when used with
Boolean values, || returns true if either operand is
true; if both are false, returns false.

Logical !expr Returns false if its single operand can be


NOT (!) converted to true; otherwise, returns true.

Operator precedence

Operator type Individual operators

member . []

call / create instance () new

negation/increment ! ~ - + ++ -- typeof void delete


Operator precedence

Operator type Individual operators

multiply/divide */%

addition/subtraction + -

bitwise shift << >> >>>

relational < <= > >= in instanceof

equality == != === !==

bitwise-and &

bitwise-xor ^

bitwise-or |

logical-and &&

logical-or ||

conditional ?:

assignment = += -= *= /= %= <<= >>= >>>= &= ^= |=

comma ,

(E)Statements

(A)Break
 The break statement exits a switch statement or a loop (for, for ...
in, while, do ... while).
 When the break statement is used with a switch statement, it breaks
out of the switch block. This will stop the execution of more
execution of code and/or case testing inside the block.
 When the break statement is used in a loop, it breaks the loop and
continues executing the code after the loop (if any).
 The break statement can also be used with an optional label
reference, to "jump out" of any JavaScript code block (see "More
Examples" below).

<!DOCTYPE html>

<html>

<body>

<p>Click the button to display what day it is today.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>

function myFunction() {

var day;

switch (new Date().getDay()) {

case 0:

day = "Sunday";

break;

case 1:

day = "Monday";
break;

case 2:

day = "Tuesday";

break;

case 3:

day = "Wednesday";

break;

case 4: Output

day = "Thursday"; Click the button to display what day it


is today.
break;
Try it
case 5:
Today is Wednesday
day = "Friday";

break;

case 6:

day = "Saturday";
break;

}
document.getElementById("demo").innerHTML = "Today is " + day;

</script>

</body>

</html>

Continue
 The continue statement breaks one iteration (in the loop) if a
specified condition occurs, and continues with the next iteration in
the loop.

 The difference between continue and the break statement, is


instead of "jumping out" of a loop, the continue statement "jumps
over" one iteration in the loop.

 However, when the continue statement is executed, it behaves


differently for different types of loops:

 In a while loop, the condition is tested, and if it is true, the loop is


executed again
 In a for loop, the increment expression (e.g. i++) is first evaluated,
and then the condition is tested to find out if another iteration
should be done

The continue statement can also be used with an optional label


reference.

<!DOCTYPE html>

<html>

<body>

<p>Click the button to do a loop which will skip the step where i is
equal to 3.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

var text = "";

var i;

for (i = 0; i < 5; i++) {

if (i === 3) {

continue;

text += "The number is " + i + "<br>";

document.getElementById("demo").innerHTML = text;

}
Click the button to do a loop which will skip
</script> the step where i is equal to 3.

Try it

</body> The number is 0


The number is 1
</html> The number is 2
The number is 4

JavaScript supports different kinds of loops:

 for - loops through a block of code a number of times


 for/in - loops through the properties of an object
 while - loops through a block of code while a specified condition is
true
 do/while - loops through a block of code once, and then repeats the
loop while a specified condition is true
Do while

 The do/while statement creates a loop that executes a block of code


once, before checking if the condition is true, then it will repeat the
loop as long as the condition is true.

 The do/while statement is used when you want to run a loop at


least one time, no matter what.

<!DOCTYPE html>
<html>
<body>
<p>Click the button to loop through a block of code as long as i is
less than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
Click the button to loop through a
<script> block of code as long as i is less than
5.
function myFunction() {
Try it
var text = ""
var i = 0; The number is 0
The number is 1
do { The number is 2
The number is 3
text += "<br>The number is " + i; The number is 4

i++;
} while (i < 5);
document.getElementById("demo").innerHTML = text;
}</script>
</body>
</html>
If else

 The if/else statement executes a block of code if a specified


condition is true. If the condition is false, another block of code
can be executed.

 The if/else statement is a part of JavaScript's "Conditional"


Statements, which are used to perform different actions based on
different conditions.

In JavaScript we have the following conditional statements:

 Use if to specify a block of code to be executed, if a specified


condition is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition
is false
 Use switch to select one of many blocks of code to be executed

<!DOCTYPE html>
<html>
<body>
<p>Clck the button to display "Good day", only if the time is less than
20:00.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var time = new Date().getHours();
if (time < 20) {
document.getElementById("demo").innerHTML = "Good day";
} Clck the button to display "Good day", only if the
time is less than 20:00.
}
Try it
</script>
</body> Good day

</html>

Switch

 The switch statement executes a block of code depending on


different cases.

 The switch statement is a part of JavaScript's "Conditional"


Statements, which are used to perform different actions based on
different conditions. Use switch to select one of many blocks of
code to be executed. This is the perfect solution for long,
nested if/else statements.

 The switch statement evaluates an expression. The value of the


expression is then compared with the values of each case in the
structure. If there is a match, the associated block of code is
executed.

 The switch statement is often used together with a break or a


default keyword (or both). These are both optional:

 The break keyword breaks out of the switch block. This will stop


the execution of more execution of code and/or case testing inside
the block. If break is omitted, the next code block in the switch
statement is executed.

 The default keyword specifies some code to run if there is no case


match. There can only be one default keyword in a switch.
Although this is optional, it is recommended that you use it, as it
takes care of unexpected cases.

<p id="demo"></p>
<script>
function myFunction() {
var text;
var fruits = document.getElementById("myInput").value;

switch(fruits) {
case "Banana":
text = "Banana is good!";
break;
case "Orange":
text = "I am not a fan of orange.";
break;
case "Apple":
text = "How you like them apples?";
break;
default:
text = "I have never heard of that fruit...";
}
document.getElementById("demo").innerHTML = text;
}
</script> Write Banana, Orange or Apple in the input
field and click the button.
</body>
The switch statement will execute a block of
</html> code based on your input.

 Try it
TRY Catch

 The try/catch/finally statement handles some or all of the errors


that may occur in a block of code, while still running code.

 Errors can be coding errors made by the programmer, errors due to


wrong input, and other unforeseeable things.

 The try statement allows you to define a block of code to be tested


for errors while it is being executed.

 The catch statement allows you to define a block of code to be


executed, if an error occurs in the try block.

 The finally statement lets you execute code, after try and catch,


regardless of the result.

Note: The catch and finally statements are both optional, but you need to
use one of them (if not both) while using the try statement.

Tip: When an error occurs, JavaScript will normally stop, and generate


an error message. Use the throw statement to create a custom error
(throw an exception). If you use throw together with try and catch, you
can control program flow and generate custom error messages.

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
try {
adddlert("Welcome guest!");
}catch(err) {
document.getElementById("demo").innerHTML = err.message;
}</script>
</body>
</html>

(F) Functions

 The function statement declares a function.


 A declared function is "saved for later use", and will be executed
later, when it is invoked (called).
 In JavaScript, functions are objects, and they have both properties
and methods.
 A function can also be defined using an expression 

Syntax
function functionName(parameters) {
    code to be executed
}
Parameter Values

Parameter Description

functionName Required. Specifies the name of the function,

which can be "saved for later use".

Function names can contain letters, digits, underscores,

and dollar signs (same rules as variables)


parameters Optional. Specifies a set of zero or more

parameter names, separated by commas. 

Function parameters are the names

listed in the function definition.

Function arguments are the real values

received by the function when it is invoked.

Inside the function, the arguments are used as local

variables.

Note: If a function is called with a missing argument,

the value of the missing

argument is set to undefined

<!DOCTYPE html>
<html>
<body>
<p>This example calls a function which returns the value of PI:</p>
<p id="demo"></p>
<script>
function myFunction() {
return Math.PI;
}
document.getElementById("demo").innerHTML = myFunction();
</script>
This example calls a function which returns the value of
</body> PI:
</html> 3.141592653589793
Object of Java Scripts

(A)Window Object
 The window object represents an open window in a browser.

 If a document contain frames (<iframe> tags), the browser creates


one window object for the HTML document, and one additional
window object for each frame.

Window Object Properties

Property Description

closed Returns a Boolean value indicating whether a window


has been closed or not

defaultStatus Sets or returns the default text in the status bar of a window

document Returns the Document object for the window


(See Document object)

frameElement Returns the <iframe> element in which the


current window is inserted

frames Returns all <iframe> elements in the current window

history Returns the History object for the window

innerHeight Returns the inner height of a window's content area


innerWidth Returns the inner width of a window's content area

length Returns the number of <iframe> elements in the current


window

localStorage Returns a reference to the local storage object used to store


data. Stores data with no expiration date

location Returns the Location object for the window)

name Sets or returns the name of a window

navigator Returns the Navigator object for the window)

opener Returns a reference to the window that created the window

outerHeight Returns the outer height of a window, including


toolbars/scrollbars

outerWidth Returns the outer width of a window, including


toolbars/scrollbars

pageXOffset Returns the pixels the current document has been scrolled
(horizontally) from the upper left corner of the window

pageYOffset Returns the pixels the current document has been scrolled
(vertically) from the upper left corner of the window

parent Returns the parent window of the current window

screen Returns the Screen object for the window 

screenLeft Returns the horizontal coordinate of the window relative to


the screen

screenTop Returns the vertical coordinate of the window relative to


the screen

screenX Returns the horizontal coordinate of the window relative to


the screen

screenY Returns the vertical coordinate of the window relative to


the screen

sessionStorage Returns a reference to the local storage object used to


store data. Stores data for one session
(lost when the browser tab is closed)

scrollX An alias of pageXOffset


scrollY An alias of pageYOffset

self Returns the current window

status Sets or returns the text in the statusbar of a window

top Returns the topmost browser window

Window Object Methods

Method Description

alert() Displays an alert box with a message and an OK button

atob() Decodes a base-64 encoded string

blur() Removes focus from the current window

btoa() Encodes a string in base-64

clearInterval() Clears a timer set with setInterval()

clearTimeout() Clears a timer set with setTimeout()


close() Closes the current window

confirm() Displays a dialog box with a message and an OK


and a Cancel button

focus() Sets focus to the current window

getComputedStyle() Gets the current computed CSS styles applied to an element

getSelection() Returns a Selection object representing the range of


text selected by the user

matchMedia() Returns a MediaQueryList object representing the


specified CSS media query string

moveBy() Moves a window relative to its current position

moveTo() Moves a window to the specified position

open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor for input
resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and height

scroll() Deprecated. This method has been replaced by the


 scrollTo() method.

scrollBy() Scrolls the document by the specified number of pixels

scrollTo() Scrolls the document to the specified coordinates

setInterval() Calls a function or evaluates an expression at specified


intervals (in milliseconds)

setTimeout() Calls a function or evaluates an expression after a


specified number of milliseconds

stop() Stops the window from loading

(B)Document Object

In the HTML DOM (Document Object Model), everything is a node:


 The document itself is a document node
 All HTML elements are element nodes
 All HTML attributes are attribute nodes
 Text inside HTML elements are text nodes
 Comments are comment nodes
 When an HTML document is loaded into a web browser, it
becomes a document object.
 The document object is the root node of the HTML document and
the "owner" of all other nodes:
(element nodes, text nodes, attribute nodes, and comment nodes).
 The document object provides properties and methods to access all
node objects, from within JavaScript.

Document Object Properties and Methods


 The following properties and methods can be used on HTML
documents:

Property / Method Description

document.activeElement Returns the currently focused

element in the document

document.addEventListener() Attaches an event handler to the

document

document.adoptNode() Adopts a node from another document

document.anchors Returns a collection of all <a> elements

in the document that have a name attribute


document.applets Returns a collection of all <applet>

elements in the document

document.baseURI Returns the absolute base URI of a

document

document.body Sets or returns the document's body (the <

document.close() Closes the output stream previously opene


document.open()

document.cookie Returns all name/value pairs of

cookies in the document

document.createAttribute() Creates an attribute node

document.createComment() Creates a Comment node with the

specified text

document.createDocumentFragment() Creates an empty DocumentFragment

node

document.createElement() Creates an Element node


document.createTextNode() Creates a Text node

document.doctype Returns the Document Type Declaration

associated with the document

document.documentElement Returns the Document Element of the

document (the <html> element)

document.documentMode Returns the mode used by the browser

to render the document

document.documentURI Sets or returns the location of the

document

document.domain Returns the domain name of the server

that loaded the document

document.domConfig Obsolete. Returns the DOM

configuration of the document


document.embeds Returns a collection of all <embed>

elements the document

document.forms Returns a collection of all <form>

elements in the document

document.getElementById() Returns the element that has the ID

attribute with the specified value

document.getElementsByClassName( Returns a NodeList containing all


)
elements with the specified class name

document.getElementsByName() Returns a NodeList containing all

elements with a specified name

document.getElementsByTagName() Returns a NodeList containing all

elements with the specified tag name

document.hasFocus() Returns a Boolean value indicating

whether the document has focus

document.head Returns the <head> element of the


document

document.images Returns a collection of all <img>

elements in the document

document.implementation Returns the DOMImplementation

object that handles this document

document.importNode() Imports a node from another document

document.inputEncoding Returns the encoding, character set,

used for the document

document.lastModified Returns the date and time the

document was last modified

document.links Returns a collection of all <a> and

<area> elements in the document that

have a href attribute

document.normalize() Removes empty Text nodes, and joins

adjacent nodes
document.normalizeDocument() Removes empty Text nodes, and joins

adjacent nodes

document.open() Opens an HTML output stream to

collect output from document.write()

document.querySelector() Returns the first element that matches

a specified CSS selector(s) in the

document

document.querySelectorAll() Returns a static NodeList containing all

elements that matches a specified CSS

selector(s) in the document

document.readyState Returns the (loading) status of the

document

document.referrer Returns the URL of the document that

loaded the current document

document.removeEventListener() Removes an event handler from the


document (that has been attached with
the addEventListener() method)

document.renameNode() Renames the specified node

document.scripts Returns a collection of <script>

elements in the document

document.strictErrorChecking Sets or returns whether error-checking

is enforced or not

document.title Sets or returns the title of the document

document.URL Returns the full URL of the HTML

document

document.write() Writes HTML expressions or JavaScript

code to a document

document.writeln() Same as write(), but adds a newline

character after each statement


HTML document objects:

 Property / Method Reason for avoiding

document.attributes Documents don't have attributes

document.hasAttributes() Documents don't have attributes

document.nextSibling Documents don't have siblings

document.nodeName This is always #document

document.nodeType This is always 9 (DOCUMENT_NODE)

document.nodeValue Documents don't have an node value

document.ownerDocument Documents don't have an owner document

document.ownerElement Documents don't have an owner element

document.parentNode Documents don't have a parent node

document.previousSibling Documents don't have siblings


document.textContent Documents don't have a text content

(C)Forms Objects

 The JavaScript Form Object is a property of the document object.


This corresponds to an HTML input form constructed with the
FORM tag. A form can be submitted by calling the JavaScript
submit method or clicking the form submit button.

You can access a <form> element by using getElementById():

<!DOCTYPE html> First name:  Donald

Duck
<html> Last name: 
Submit
<body>
<h3>A demonstration of how to access a FORM element</h3>
<form id="myForm" action="form_action.asp">
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit">
</form>
<p>Click the "Try it" button to get the URL for where to send the form
data when the form above is submitted.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myForm").action;
document.getElementById("demo").innerHTML = x;}
</script>
</body>
</html>
Form Object Properties

 action - This specifies the URL and CGI script file name the form
is to be submitted to. It allows reading or changing the ACTION
attribute of the HTML FORM tag.
 elements - An array of fields and elements in the form.
 encoding - This is a read or write string. It specifies the encoding
method the form data is encoded in before being submitted to the
server. It corresponds to the ENCTYPE attribute of the FORM tag.
The default is "application/x-www-form-urlencoded". Other
encoding includes text/plain or multipart/form-data.
 length - The number of fields in the elements array. I.E. the length
of the elements array.
 method - This is a read or write string. It has the value "GET" or
"POST".
 name - The form name. Corresponds to the FORM Name attribute.
 target - The name of the frame or window the form submission
response is sent to by the server. Corresponds to the FORM
TARGET attribute.

Form Objects

Forms have their own objects.

 button - An GUI pushbutton control. Methods are click(), blur(),


and focus(). Attributes:
o name - The name of the button
o type - The object's type. In this case, "button".
o value - The string displayed on the button.

 checkbox - An GUI check box control. Methods are click(), blur(),


and focus(). Attributes:
o checked - Indicates whether the checkbox is checked. This is
a read or write value.
o defaultChecked - Indicates whether the checkbox is checked
by default. This is a read only value.
o name - The name of the checkbox.

o type - Type is "checkbox".


o value - A read or write string that specifies the value returned
when the checkbox is selected.

 FileUpload - This is created with the INPUT type="file". This is


the same as the text element with the addition of a directory
browser. Methods are blur(), and focus().
 Attributes:
o name - The name of the FileUpload object.
o type - Type is "file".
o value - The string entered which is returned when the form is
submitted.

 hidden - An object that represents a hidden form field and is used


for client/server communications. No methods exist for this object.
Attributes:
o name - The name of the Hidden object.
o type - Type is "hidden".
o value - A read or write string that is sent to the server when
the form is submitted.

 password - A text field used to send sensitive data to the server.


Methods are blur(), focus(), and select(). Attributes:
o defaultValue - The default value.
o name - The name of the password object."
o type - Type is "password".
o value - A read or write string that is sent to the server when
the form is submitted.

 radio - A GUI radio button control. Methods are click(), blur(), and
focus(). Attributes:
o checked - Indicates whether the radio button is checked. This
is a read or write value.
o defaultChecked - Indicates whether the radio button is
checked by default. This is a read only value.
o length - The number of radio buttons in a group.
o name - The name of the radio button.
o type - Type is "radio".
o value - A read or write string that specifies the value returned
when the radio button is selected.

 reset - A button object used to reset a form back to default values.


Methods are click(), blur(), and focus(). Attributes:
o name - The name of the reset object.
o type - Type is "reset".
o value - The text that appears on the button. By default it is
"reset".

 select - A GUI selection list. This is basically a drop down list.


Methods are blur(), and focus(). Attributes:
o length - The number of elements contained in the options
array.
o name - The name of the selection list.
o options - An array each of which identifies an options that
may be selected in the list.
o selectedIndex - Specifies the current selected option within
the select list
o type - Type is "select".

 submit - A submit button object. Methods are click(), blur(), and


focus(). Attributes:
o name - The name of the submit button.
o type - Type is "submit".
o value - The text that will appear on the button.
 text - A GUI text field object. Methods are blur(), focus(), and
select(). Attributes:
o defaultValue - The text default value of the text field.
o name - The name of the text field.
o type - Type is "text".
o value - The text that is entered and appears in the text field. It
is sent to the server when the form is submitted.
 textarea - A GUI text area field object. Methods are blur(), focus(),
and select(). Attributes:
o defaultValue - The text default value of the text area field.
o name - The name of the text area.
o type - Type is textarea.
o value- The text that is entered and appears in the text area
field. It is sent to the server when the form is submitted.

Form Object Methods

 reset() - Used to reset the form elements to their default values.


 submit() - Submits the form as though the submit button were
pressed by the user.

 Events

 onReset
 onSubmit

(C) Text Areas and Text Boxes

(A)Text Areas

The JavaScript TextArea Object is a property of the form object.


Textarea syntax is:

<TEXTAREA NAME="" ROWS="10" COLS="40"


onBlur="blurHandlerRouting">
Displayed Text
</TEXTAREA>

Here's how it looks:

The NAME, ROWS, and COLS values are required. Three optional
handlers may be specified which are "onBlur", "onChange", and
"onSelect". If these handlers are used, the appropriate function must
exist to support the action.

Properties

 defaultValue - The text string value that is initially displayed.


 form - The form object that includes the textArea object.
 name - The name of the textArea object. This object should always
have a name.
 type - The type of element which is textarea.
 value - The value of the textArea object.
 rows - The number of rows displayed in the text area.
 cols - The number of columns displayed in the text area.
 Wrap may be set to one of the following values:
o OFF - Default, lines are not wrapped.
o PHYSICAL - Wrap lines and place new line characters
where the line wraps.
o VIRTUAL - Wrap lines on the screen, but receive them as
one line.

Methods

 blur() - Takes the focus away from the textarea object.


 focus() - Gives the focus to the textarea object.
 select() - Selects the contents of the textarea.

Events

 onBlur
 onChange
 onFocus
 onSelects

(B)Text Boxes

The JavaScript Text Object is a property of the form object. Example


code:

<INPUT TYPE=TEXT NAME="firstname">

Here's how it looks:

Properties

 defaultValue - The text default value of the text field.


 form - The form that contains the text object.
 name - The name of the text field.
 type - Type is "text".
 value - The text that is entered and appears in the text field. It is
sent to the server when the form is submitted.

Methods

 blur() - Removes the input focus from the text field.


 focus() - Give the input focus to the text field.
 select() - Select the contents of the text field

Events

 onBlur
 onChange
 onFocus
 onSelect

(D)Buttons

 An button object refers to a clickable button in an html page.


 Button is created by setting the value of type attribute of an html
input tag as button (for example <input type="button"
value="Send">).
 Button objects can be accessed
by document.myform.buttonname, where myform is the name of
the form containing the button object and button name is the name
of the button. document.myform.elements[i], where i is the
position of the button within form.
 Javascript Button Objects Property

Name Description V

form Refers to the associated form. I

name Indicate the name attribute. I

type Indicate the type attribute. I

value Indicate the value attribute. I

 JavaScript Button Objects Methods

Name Description

blur Focus lost from the button.

click Indicate a mouse click on the button.

focus To get focus to the button.

(E)Radio Buttons and Check Boxes

(A)Radio Buttons
 Checking radio buttons on a form is a little trickier. You have to
loop through each button, testing for a value of checked, which
means it was selected.
 one radio button in a group can be selected, so if you find a value
of checked you can break out of the loop.
 If no radio button was checked then you can return a value of false.
If any one of them is checked then you can return a value of true.
Here's the code for your radio button function:

 First we set up a variable called payment and set it to be a blank


string. This will hold a value of checked if the user has selected
a radio button and will be empty otherwise. The next line is this:

var len = document.frmOne.payment.length;

 On the right of the equal sign we again try to access a form


element. This time, the element we want has a name of
payment. This came from the HTML:

<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card


<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal

 If you want to group radio buttons together you give them the
same name. You can then access this name in your code. But
look at what is now on the end:

document.frmOne.payment.length;
When we accessed the text box element like this we had value on the
end. This time we have length. Length is how many radio button are
in the group. We can use this length in the loop:

for (i = 0; i < len; i++) {

if ( document.frmOne.payment[i].checked ) {

payment = document.frmOne.payment[i].value;
break;

The loop goes round and around while the variable called i is less
than the length of the radio buttons. Inside of the loop we have this:

if ( document.frmOne.payment[i].checked ) {

payment = document.frmOne.payment[i].value;
break;

This IF statements checks each radio button for a value of checked.


But we can't just say:

document.frmOne.payment.checked

 The payment part refers to the whole group of radio buttons. To


get at each individual radio button you can use a pair of square
brackets. Inside the square brackets you type a number.
 The number corresponds to a particular button. So payment[0]
is the first button, payment[1] is the second button, and so on.
 If the IF statement detects that any one of these buttons has a
value of checked it puts that value into the payment variable:

payment = document.frmOne.payment[i].value;

 We can then break out of the loop because we know that the
user has selected a radio button.
 The IF statement after the loop checks what's inside the variable
called payment. It does exactly the same thing as the email
check box.
 The only difference is that it places an error message besides the
radio buttons rather than besides the text box.
 Test it out. Click your submit button without selecting a radio
button. You should see this:

(B) Check Boxes

The final function we need is for the checkbox. You can have 1 or more
checkboxes on a form. We only have 1, so checking it is fairly
straightforward. If you have more than checkbox, though, you do the
testing in exactly the same way as for radio buttons.

But here's the code for the checkCheckbox function:

The IF statement just tests the terms HTML element (a checkbox) for a


value of checked. If it has been checked then we can return a value of
true, as the user has agreed to the terms and conditions. If the checkbox
has not been checked, the value will be "undefined" and we can return a
value of false.

Test it out. Leave the check box unchecked. Click the submit button and
you'll see this:

(F)The Select Object

The JavaScript Select Object is a property of the form object. The


Option object(s) appear inside it as in the following code:
<SELECT NAME="state" SIZE=0>
<OPTION VALUE="0">
<OPTION VALUE="1">AL
<OPTION VALUE="2">AK
<OPTION VALUE="3">AR
</SELECT>
It looks like:

Properties

 form - The form that contains the selection list.


 length - The number of elements contained in the options array.
 name - The name of the selection list.
 options - An array each of which identifies an options that may be
selected in the list.
 selectedIndex - Specifies the current selected option within the
select list
 type - Type is "select".

Methods

 blur() - Removes the input focus from the selection list.


 focus() - Gives the input focus to the selection list.

Events

 onBlur
 onChange
 onFocus

Other Object

(A)The Date Object


 The Date object is a datatype built into the JavaScript language.
Date objects are created with the new Date( ) as shown below.
 Once a Date object is created, a number of methods allow you to
operate on it. Most methods simply allow you to get and set the
year, month, day, hour, minute, second, and millisecond fields of
the object, using either local time or UTC (universal, or GMT)
time.
 The ECMAScript standard requires the Date object to be able to
represent any date and time, to millisecond precision, within 100
million days before or after 1/1/1970. This is a range of plus or
minus 273,785 years, so JavaScript can represent date and time till
the year 275755.
Syntax
You can use any of the following syntaxes to create a Date object using
Date() constructor.

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.
Here is a description of the parameters −
 No Argument − With no arguments, the Date() constructor
creates a Date object set to the current date and time.
 milliseconds − When one numeric argument is passed, it is taken
as the internal numeric representation of the date in milliseconds,
as returned by the getTime() method. For example, passing the
argument 5000 creates a date that represents five seconds past
midnight on 1/1/70.
 datestring − When one string argument is passed, it is a string
representation of a date, in the format accepted by
the Date.parse()method.
 7 agruments − To use the last form of the constructor shown
above. Here is a description of each argument:
o year − Integer value representing the year. For compatibility
(in order to avoid the Y2K problem), you should always
specify the year in full; use 1998, rather than 98.
o month − Integer value representing the month, beginning
with 0 for January to 11 for December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-
hour scale).
o minute − Integer value representing the minute segment of a
time reading.
o second − Integer value representing the second segment of a
time reading.
o millisecond − Integer value representing the millisecond
segment of a time reading.
Date Properties
Here is a list of the properties of the Date object along with their
description.

Property Description

constructo Specifies the function that creates an object's


r prototype.

prototype The prototype property allows you to add properties


and methods to an object

In the following sections, we will have a few examples to demonstrate


the usage of different Date properties.
Date Methods
Here is a list of the methods used with Date and their description.

Method Description

Date() Returns today's date and time


getDate() Returns the day of the month for the
specified date according to local time.

getDay() Returns the day of the week for the


specified date according to local time.

getFullYear() Returns the year of the specified date


according to local time.

getHours() Returns the hour in the specified date


according to local time.

getMilliseconds() Returns the milliseconds in the specified


date according to local time.

getMinutes() Returns the minutes in the specified date


according to local time.

getMonth() Returns the month in the specified date


according to local time.

getSeconds() Returns the seconds in the specified date


according to local time.

getTime() Returns the numeric value of the specified


date as the number of milliseconds since
January 1, 1970, 00:00:00 UTC.

getTimezoneOffset() Returns the time-zone offset in minutes


for the current locale.

getUTCDate() Returns the day (date) of the month in the


specified date according to universal time.
getUTCDay() Returns the day of the week in the
specified date according to universal time.

getUTCFullYear() Returns the year in the specified date


according to universal time.

getUTCHours() Returns the hours in the specified date


according to universal time.

getUTCMilliseconds() Returns the milliseconds in the specified


date according to universal time.

getUTCMinutes() Returns the minutes in the specified date


according to universal time.

getUTCMonth() Returns the month in the specified date


according to universal time.

getUTCSeconds() Returns the seconds in the specified date


according to universal time.

getYear() Deprecated - Returns the year in the


specified date according to local time. Use
getFullYear instead.

setDate() Sets the day of the month for a specified


date according to local time.

setFullYear() Sets the full year for a specified date


according to local time.

setHours() Sets the hours for a specified date


according to local time.
setMilliseconds() Sets the milliseconds for a specified date
according to local time.

setMinutes() Sets the minutes for a specified date


according to local time.

setMonth() Sets the month for a specified date


according to local time.

setSeconds() Sets the seconds for a specified date


according to local time.

setTime() Sets the Date object to the time


represented by a number of milliseconds
since January 1, 1970, 00:00:00 UTC.

setUTCDate() Sets the day of the month for a specified


date according to universal time.

setUTCFullYear() Sets the full year for a specified date


according to universal time.

setUTCHours() Sets the hour for a specified date


according to universal time.

setUTCMilliseconds() Sets the milliseconds for a specified date


according to universal time.

setUTCMinutes() Sets the minutes for a specified date


according to universal time.

setUTCMonth() Sets the month for a specified date


according to universal time.
setUTCSeconds() Sets the seconds for a specified date
according to universal time.

setYear() Deprecated - Sets the year for a specified


date according to local time. Use
setFullYear instead.

toDateString() Returns the "date" portion of the Date as a


human-readable string.

toGMTString() Deprecated - Converts a date to a string,


using the Internet GMT conventions. Use
toUTCString instead.

toLocaleDateString() Returns the "date" portion of the Date as a


string, using the current locale's
conventions.

toLocaleFormat() Converts a date to a string, using a format


string.

toLocaleString() Converts a date to a string, using the


current locale's conventions.

toLocaleTimeString() Returns the "time" portion of the Date as a


string, using the current locale's
conventions.

toSource() Returns a string representing the source


for an equivalent Date object; you can use
this value to create a new object.

toString() Returns a string representing the specified


Date object.
toTimeString() Returns the "time" portion of the Date as a
human-readable string.

toUTCString() Converts a date to a string, using the


universal time convention.

valueOf() Returns the primitive value of a Date


object.

Converts a date to a string, using the universal time convention.

Date Static Methods


In addition to the many instance methods listed previously, the Date
object also defines two static methods. These methods are invoked
through the Date() constructor itself.

Method Description

Date.parse( ) Parses a string representation of a date and


time and returns the internal millisecond
representation of that date.

Date.UTC( ) Returns the millisecond representation of the


specified UTC date and time.
(B) The Math Object

 The math object provides you properties and methods for


mathematical constants and functions. Unlike other global
objects, Math is not a constructor.
 All the properties and methods of Math are static and can be
called by using Math as an object without creating it.
 Thus, you refer to the constant pi as Math.PI and you call
the sine function asMath.sin(x), where x is the method's
argument.
Syntax
The syntax to call the properties and methods of Math are as follows

var pi_val = Math.PI;


var sine_val = Math.sin(30);
Math Properties
Here is a list of all the properties of Math and their description.

Property Description

E\ Euler's constant and the base of natural logarithms,


approximately 2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.

PI Ratio of the circumference of a circle to its diameter,


approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the square
root of 2, approximately 0.707.

SQRT2 Square root of 2, approximately 1.414.

In the following sections, we will have a few examples to demonstrate


the usage of Math properties.
Math Methods
Here is a list of the methods associated with Math object and their
description

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

atan2() Returns the arctangent of the quotient of its


arguments.

ceil() Returns the smallest integer greater than or equal to a


number.

cos() Returns the cosine of a number.

exp() Returns EN, where N is the argument, and E is Euler's


constant, the base of the natural logarithm.
floor() Returns the largest integer less than or equal to a
number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base


exponent.

random() Returns a pseudo-random number between 0 and 1.

round() Returns the value of a number rounded to the nearest


integer.

sin() Returns the sine of a number.

sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

toSource() Returns the string "Math".

(C)The String Object

 The String object lets you work with a series of characters; it


wraps Javascript's string primitive data type with a number of
helper methods.
 As JavaScript automatically converts between string primitives
and String objects, you can call any of the helper methods of the
String object on a string primitive.
Syntax
Use the following syntax to create a String object −

var val = new String(string);


The String parameter is a series of characters that has been properly
encoded.
String Properties
Here is a list of the properties of String object and their description.

Property Description

constructo Returns a reference to the String function that created


r the object.

length Returns the length of the string.

prototype The prototype property allows you to add properties


and methods to an object.

In the following sections, we will have a few examples to demonstrate


the usage of String properties.

String Methods
Here is a list of the methods available in String object along with their
description.

Method Description
charAt() Returns the character at the specified
index.

charCodeAt() Returns a number indicating the Unicode


value of the character at the given index.

concat() Combines the text of two strings and


returns a new string.

indexOf() Returns the index within the calling String


object of the first occurrence of the
specified value, or -1 if not found.

lastIndexOf() Returns the index within the calling String


object of the last occurrence of the
specified value, or -1 if not found.

localeCompare() Returns a number indicating whether a


reference string comes before or after or is
the same as the given string in sort order.

match() Used to match a regular expression against


a string.

replace() Used to find a match between a regular


expression and a string, and to replace the
matched substring with a new substring.

search() Executes the search for a match between a


regular expression and a specified string.

slice() Extracts a section of a string and returns a


new string.
split() Splits a String object into an array of
strings by separating the string into
substrings.

substr() Returns the characters in a string


beginning at the specified location through
the specified number of characters.

substring() Returns the characters in a string between


two indexes into the string.

toLocaleLowerCase( The characters within a string are


) converted to lower case while respecting
the current locale.

toLocaleUpperCase() The characters within a string are


converted to upper case while respecting
the current locale.

toLowerCase() Returns the calling string value converted


to lower case.

toString() Returns a string representing the specified


object.

toUpperCase() Returns the calling string value converted


to uppercase.

valueOf() Returns the primitive value of the


specified object.

String HTML Wrappers


Here is a list of the methods that return a copy of the string wrapped
inside an appropriate HTML tag.
Method Description

anchor() Creates an HTML anchor that is used as a hypertext


target.

big() Creates a string to be displayed in a big font as if it


were in a <big> tag.

blink() Creates a string to blink as if it were in a <blink> tag.

bold() Creates a string to be displayed as bold as if it were in


a <b> tag.

fixed() Causes a string to be displayed in fixed-pitch font as if


it were in a <tt> tag

fontcolor() Causes a string to be displayed in the specified color


as if it were in a <font color="color"> tag.

fontsize() Causes a string to be displayed in the specified font


size as if it were in a <font size="size"> tag.

italics() Causes a string to be italic, as if it were in an <i> tag.

link() Creates an HTML hypertext link that requests another


URL.

small() Causes a string to be displayed in a small font, as if it


were in a <small> tag.

strike() Causes a string to be displayed as struck-out text, as if


it were in a <strike> tag.

sub() Causes a string to be displayed as a subscript, as if it


were in a <sub> tag

sup() Causes a string to be displayed as a superscript, as if it


were in a <sup> tag

(D)Regular Expressions

 A regular expression is an object that describes a pattern of


characters.
 The JavaScript RegExp class represents regular expressions, and
both String and RegExp define methods that use regular
expressions to perform powerful pattern-matching and search-
and-replace functions on text.
Syntax
A regular expression could be defined with the RegExp () constructor,
as follows −
var pattern = new RegExp(pattern, attributes);

or simply

var pattern = /pattern/attributes;


Here is the description of the parameters −
 pattern − A string that specifies the pattern of the regular
expression or another regular expression.
 attributes − An optional string containing any of the "g", "i", and
"m" attributes that specify global, case-insensitive, and multiline
matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of
regular expressions. They are used to find a range of characters.

Expressio Description
n

[...] Any one character between the brackets.

[^...] Any one character not between the brackets.

[0-9] It matches any decimal digit from 0 through 9.

[a-z] It matches any character from lowercase a through


lowercase z.

[A-Z] It matches any character from uppercase A through


uppercase Z.

[a-Z] It matches any character from lowercase a through


uppercase Z.

The ranges shown above are general; you could also use the range [0-3]
to match any decimal digit ranging from 0 through 3, or the range [b-v]
to match any lowercase character ranging from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single
characters can be denoted by a special character. Each special character
has a specific connotation. The +, *, ?, and $ flags all follow a character
sequence.

Expressio Description
n

p+ It matches any string containing one or more p's.

p* It matches any string containing zero or more p's.

p? It matches any string containing at most one p.

p{N} It matches any string containing a sequence of N p's

p{2,3} It matches any string containing a sequence of two or


three p's.

p{2, } It matches any string containing a sequence of at least


two p's.

p$ It matches any string with p at the end of it.

^p It matches any string with p at the beginning of it.


Examples
Following examples explain more about matching characters.

Expression Description

[^a-zA-Z] It matches any string not containing any of the


characters ranging from a through z and A through Z.

p.p It matches any string containing p, followed by any


character, in turn followed by another p.

^.{2}$ It matches any string containing exactly two


characters.

<b>(.*)</b It matches any string enclosed within <b> and </b>.


>

p(hp)* It matches any string containing a p followed by zero


or more instances of the sequence hp.

Literal characters
Character Description

Alphanumeri Itself
c

\0 The NUL character (\u0000)

\t Tab (\u0009)

\n Newline (\u000A)
\v Vertical tab (\u000B)

\f Form feed (\u000C)

\r Carriage return (\u000D)

\xnn The Latin character specified by the hexadecimal


number nn; for example, \x0A is the same as \n

\uxxxx The Unicode character specified by the hexadecimal


number xxxx; for example, \u0009 is the same as \t

\cX The control character ^X; for example, \cJ is


equivalent to the newline character \n

Metacharacters
 A metacharacter is simply an alphabetical character preceded by a
backslash that acts to give the combination a special meaning.
 For instance, you can search for a large sum of money using the
'\d' metacharacter: /([\d]+)000/, Here \d will search for any string
of numerical character.
 The following table lists a set of metacharacters which can be
used in PERL Style Regular Expressions.

Character Description

. a single character

\s a whitespace character (space, tab, newline)


\S non-whitespace character

\d a digit (0-9)

\D a non-digit

\w a word character (a-z, A-Z, 0-9, _)

\W a non-word character

[\b] a literal backspace (special case).

[aeiou] matches a single character in the given set

[^aeiou] matches a single character outside the given set

(foo|bar|baz) matches any of the alternatives specified

Modifiers
Several modifiers are available that can simplify the way you work
withregexps, like case sensitivity, searching in multiple lines, etc.

Modifier Description

i Perform case-insensitive matching.

m Specifies that if the string has newline or carriage return


characters, the ^ and $ operators will now match against
a newline boundary, instead of a string boundary

g Performs a global matchthat is, find all matches rather


than stopping after the first match.

RegExp Properties
Here is a list of the properties associated with RegExp and their
description.

Property Description

constructo Specifies the function that creates an object's


r prototype.

global Specifies if the "g" modifier is set.

ignoreCase Specifies if the "i" modifier is set.

lastIndex The index at which to start the next match.

multiline Specifies if the "m" modifier is set.

source The text of the pattern.

In the following sections, we will have a few examples to demonstrate


the usage of RegExp properties.
RegExp Methods
Here is a list of the methods associated with RegExp along with their
description.

Method Description

exec() Executes a search for a match in its string parameter.

test() Tests for a match in its string parameter.


toSource() Returns an object literal representing the specified
object; you can use this value to create a new object.

toString() Returns a string representing the specified object.

(E)Arrays

The Array object lets you store multiple values in a single variable. It


stores a fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more useful
to think of an array as a collection of variables of the same type.
Syntax
Use the following syntax to create an Array object −

var fruits = new Array( "apple", "orange", "mango" );


The Array parameter is a list of strings or integers. When you specify a
single numeric parameter with the Array constructor, you specify the
initial length of the array. The maximum length allowed for an array is
4,294,967,295.
You can create array by simply assigning values as follows −

var fruits = [ "apple", "orange", "mango" ];


You will use ordinal numbers to access and to set values inside an array
as follows.

fruits[0] is the first element


fruits[1] is the second element
fruits[2] is the third element

Array Properties
Here is a list of the properties of the Array object along with their
description.

Property Description

constructo Returns a reference to the array function that created


r the object.

index The property represents the zero-based index of the


match in the string

input This property is only present in arrays created by


regular expression matches.

length Reflects the number of elements in an array.


prototype The prototype property allows you to add properties
and methods to an object.

In the following sections, we will have a few examples to illustrate the


usage of Array properties.

Array Methods
Here is a list of the methods of the Array object along with their
description.

Method Description

concat() Returns a new array comprised of this array joined


with other array(s) and/or value(s).

every() Returns true if every element in this array satisfies


the provided testing function.

filter() Creates a new array with all of the elements of this


array for which the provided filtering function
returns true.

forEach() Calls a function for each element in the array.

indexOf() Returns the first (least) index of an element within


the array equal to the specified value, or -1 if none
is found.

join() Joins all elements of an array into a string.

lastIndexOf() Returns the last (greatest) index of an element


within the array equal to the specified value, or -1
if none is found.
map() Creates a new array with the results of calling a
provided function on every element in this array.

pop() Removes the last element from an array and


returns that element.

push() Adds one or more elements to the end of an array


and returns the new length of the array.

reduce() Apply a function simultaneously against two


values of the array (from left-to-right) as to reduce
it to a single value.

reduceRight( Apply a function simultaneously against two


) values of the array (from right-to-left) as to reduce
it to a single value.

reverse() Reverses the order of the elements of an array --


the first becomes the last, and the last becomes the
first.

shift() Removes the first element from an array and


returns that element.

slice() Extracts a section of an array and returns a new


array.

some() Returns true if at least one element in this array


satisfies the provided testing function.

toSource() Represents the source code of an object

sort() Sorts the elements of an array


splice() Adds and/or removes elements from an array.

toString() Returns a string representing the array and its


elements.

unshift() Adds one or more elements to the front of an array


and returns the new length of the array.
UNIT -4
DHTML

Introduction

 Dynamic HTML, or DHTML, is an umbrella term for a collection


of technologies used together to create interactive and
animated web sites by using a combination of a static markup
language (such as HTML), a client-side scripting language (such
as JavaScript), a presentation definition language (such as CSS),
and the Document Object Model (DOM).
 The application of DHTML was introduced by Microsoft with the
release of Internet Explorer 4 in 1997.
 DHTML allows scripting languages to change variables in a web
page's definition language, which in turn affects the look and
function of otherwise "static" HTML page content, after the page
has been fully loaded and during the viewing process.
 Thus the dynamic characteristic of DHTML is the way it functions
while a page is viewed, not in its ability to generate a unique page
with each page load.
 By contrast, a dynamic web page is a broader concept, covering
any web page generated differently for each user, load occurrence,
or specific variable values.
 This includes pages created by client-side scripting, and ones
created by server-side scripting (such
asPHP, Perl, JSP or ASP.NET) where the web server generates
content before sending it to the client.
 DHTML is differentiated from Ajax by the fact that a DHTML
page is still request/reload-based. With DHTML, there may not be
any interaction between the client and server after the page is
loaded; all processing happens in JavaScript on the client side.
 By contrast, an Ajax page uses features of DHTML to initiate a
request (or 'subrequest') to the server to perform additional actions.
 For example, if there are multiple tabs on a page, pure DHTML
approach would load the contents of all tabs and then dynamically
display only the one that is active, while AJAX could load each tab
only if (and when) it is really needed.
Uses

DHTML allows authors to add effects to their pages that are otherwise
difficult to achieve. In short words: scripting language is changing
the DOM and page style.
Simply put, DHTML is the combination of HTML, CSS and JavaScript.

 Animate text and images in their document, independently moving


each element from any starting point to any ending point, following a
predetermined path or one chosen by the user.
 Embed a ticker that automatically refreshes its content with the
latest news, stock quotes, or other data.
 Use a form to capture user input, and then process, verify and
respond to that data without having to send data back to the server.
 Include rollover buttons or drop-down menus.
1. A less common use is to create browser-based action games.
Although a number of games were created using DHTML during
the late 1990s and early 2000s, differences between browsers made
this difficult: many techniques had to be implemented in code to
enable the games to work on multiple platforms.
2. Recently browsers have been converging towards web standards,
which has made the design of DHTML games more viable. Those
games can be played on all major browsers and they can also be
ported to Plasma for KDE, Widgets for OS X and Gadgets
for Windows Vista, which are based on DHTML code.
3. The term "DHTML" has fallen out of use in recent years as it was
associated with practices and conventions that tended to not work
well between various web browsers. DHTML may now be referred
to as unobtrusive JavaScript coding (DOM Scripting), in an effort
to place an emphasis on agreed-upon best practices while allowing
similar effects in an accessible, standards-compliant way.
4. DHTML support with extensive DOM access was introduced
with Internet Explorer 4.0.
5. Although there was a basic dynamic system with Netscape
Navigator 4.0, not all HTML elements were represented in the
DOM.
6. When DHTML-style techniques became widespread, varying
degrees of support among web browsers for the technologies
involved made them difficult to develop and debug.
7. Development became easier when Internet Explorer 5.0+, Mozilla
Firefox 2.0+, and Opera 7.0+ adopted a shared DOM inherited
fromECMAScript.
More recently, JavaScript libraries such as jQuery have abstracted away
many of the day-to-day difficulties in cross-browser DOM manipulation.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DHTML example</title>
</head>
<body>
<div id="navigation"></div>

<script>
var init = function () {
myObj = document.getElementById("navigation");
// ... manipulate myObj
};
window.onload = init;
</script>

<!--
Often the code is stored in an external file; this is done
by linking the file that contains the JavaScript.
This is helpful when several pages use the same script:
-->
<script src="myjavascript.js"></script>
</body>
</html>

Cascading Style Sheet (CSS)

(A)Coding
 CSS use for how to display HTML elements look and formatting
are set using CSS properties.
 Using CSS properties you can change every single elements style
can change as you like.
 CSS Style sheet create and include with webpage is very easly.
Using CSS Style Sheet update webpage formatting and maintain
consistency across multiple webpages.
 CSS properties define either individually or group of element and
best way to done while webpage is being created. Style Sheets
like a 'blueprints' because its hold a group of style related
properties and values.
Define CSS Comments
CSS comment you can define in to your <style> section or Style Sheet
using /* and */ (follwing example line 2 and line 4 comment define).
CSS Comment Example
/* Header style start from here */
#header {
color:purple; /* Default header color */
margin-left:20px;
}
#header .logo {
font-size:16px;
background-color:#FF6633;
}
Advantage of CSS
Easy Manage : CSS with you can better manage whole webpage. CSS
allow to manage entire site elements looks and formatting in single
style sheet file.
Global Change : CSS Style Sheet changes apply to global change for
all webpage. When Style Sheet appear with webpage it's know as
Cascading Style Sheet.
Save time : When we create HTML document, we define separate set
attributes value in each element. but it is limited use. But, CSS give a
lot of flexibility to set properties and values either group of element or
single element. So it's benifit to avoid same code write again and
again.
Easy Maintain/Update : CSS style sheet maintain easier and anytime
you can edit elements properties and values.
3 way to write CSS : You can write CSS styles 3 way Inline element
line (scope is only that element), Internal style write in header section
(scope is only that webpage), or External style sheets write in
external .css extesion files. External style sheets enable you to change
the elements and layout style of all the pages in a Web site, just by
editing one single file.
Page Load Faster : Webpage with style sheets take a bit of second to
load very fastly.
(B)Properties of Text

 CSS TEXT properties are various type like text color, text-align,
text-decoration, letter-spacing and many more properties.
 Using this propeties you can change the text formatting style.
 Following are some CSS text properties listed. Using these
properties you can play with text formatting style.

CSS Color
CSS color property use to set the Text color. The color value can be
specified following three types:

1. Color Name: Orange


2. Color Hexadecimal Code: #FFA500
3. Color RGB: rgb(255, 165, 0)

Example Code:
<body>
<p style="color:orange;">CSS TEXT color name orange</p>
<p style="color:#FFA500;">CSS TEXT color hexadecimal code
#FFA500</p>
<p style="color:rgb(255,156,0);">CSS TEXT RGB color code
rgb(255,156,0)</p>
</body>

Run it...   »
Example Result:
CSS TEXT color name orange
CSS TEXT color hexadecimal code #FFA500
CSS TEXT RGB color code rgb(255,156,0)
CSS text-align
CSS text-align property use to set the horizontal alignment of text.
text-align posible value center, left, right, or justify.
When you set text-align property value justify than the effect is both
width (left or right) equal like newspaper or books type.
Example Code:
<body>
<p style="text-align:right;">CSS TEXT align right</p>
<p style="text-align:center;">CSS TEXT align center</p>
<p style="text-align:left;">CSS TEXT align left</p>
<p style="text-align:justify;">Hello reader, this ia example of
CSS text-align justify type. Both side left
and right are equal. Its like newspaper or book type. Hello
reader, this ia example of CSS text-align justify type.
Both side left and right are equal. Its like newspaper or book
type. Hello reader, this ia example of CSS text-align
justify type. Both side left and right are equal. Its like newspaper
or book type.</p>
</body>

Run it...   »
Example Result:
CSS TEXT align right
CSS TEXT align center
CSS TEXT align left

Hello reader, this ia example of CSS text-align justify type. Both side
left and right are equal. Its like newspaper or book type. Hello reader,
this ia example of CSS text-align justify type. Both side left and right are
equal. Its like newspaper or book type. Hello reader, this ia example of
CSS text-align justify type. Both side left and right are equal. Its like
newspaper or book type.
CSS text-indent
CSS text-indent property is used to set the paragraph first line leftside
leave the blank space.
Example Code:
<body>
<p style="text-indent:35px;">This paragraph is example of CSS
text-indent property and value set 35px (pixel).
So it means paragraph first line leftside leave blank space end of
blank space start a first line paragraph text.</p>
</body>

Run it...   »
Example Result:
This paragraph is example of CSS text-indent property and value set
35px (pixel). So it means paragraph first line leftside leave blank space
end of blank space start a first line paragraph text.

CSS text-decoration
CSS text-decoration property use to decorate the text.
CSS text-decoration posible value underline, overline, blink, through
etc.
Example Code:
<body>
<p style="text-decoration:underline;">Text is underline
decorate</p>
<p style="text-decoration:overline;">Text is overline
decorate</p>
<p style="text-decoration:blink;">Text is blink decorate</p>
<p style="text-decoration:line-through;">Text is line delete
decorate</p>
<p style="text-decoration:none;">Text is Nothing any decorate
value</p>
</body>
Run it...   »
Example Result:
Text is underline decorate
Text is overline decorate
Text is blink decorate
Text is line delete decorate
Text is nothing any decorate value
CSS text-transformation
 CSS text-transformation property use to text transform.
 CSS text-transformation posible value capitalize, lowercase and
uppercase in a text.
 CSS text-transformation property value capitalize, it means first
letter capital for all word.
Example Code:
<body>
<p style="text-transform:capitalize;">this line transform
capital</p>
<p style="text-transform:lowercase;">this line transform
Lowercase</p>
<p style="text-transform:uppercase;">this line transform
Uppercase</p>
</body>
Run it...   »
Example Result:
This Line Transform Capital.
this line transform lowercase.
THIS LINE TRANSFORM UPPERCASE.
CSS letter-spacing
CSS letter-spacing property set blank space between each two letter.
Example Code:
<body>
<p style="letter-spacing:5px">This text is letter spacing</p>
</body>

Run it...   »
Example Result:
This text is letter spacing

CSS word-spacing
CSS word-spacing property set blank space between each two word.
Example Code:
<body>
<p style="word-spacing:25px">This text is Word Spacing</p>
</body>

Run it...   »
Example Result:
This text is Word Spacing

CSS white-space
CSS white-space property use to set a predefine task. CSS white-space
possible value is normal, pre.

Example Code:
<body>
<p style="white-space:pre">This text is Predefined Area
Predefined area second line</p>
</body>

Run it...   »
Example Result:
This text is Predefined Area

Predefined area second line

CSS text-shadow
CSS text-shadow property is use to decorate text and apply shadow
effect style.
Example Code:
<body>
<p style="text-shadow:4px 4px 8px orange;">This text is
Text Shadow Effect</p>
</body>

Run it...   »
Example Result:
This text is Text Shadow Effect

(C)Property Values

All CSS Properties Listed Alphabetically based on CSS2 (Cascading


Style Sheet 2). All CSS properties list alphabetically to help you
quickly find the property you are finding. CSS properties are used to
apply styles to create structured Layout documents, such as those
created with HTML or XML.
View All CSS Properties Listed GroupWise

All CSS Properties Listed Alphabetically


background  clip max-width
background- color min-height
attachment  content min-width
background-color counter-increment outline
background-image counter-reset outline-color
background-position  cursor outline-style
background-repeat  direction outline-width
border  display overflow
border-collapse  empty-cells padding
border-color  float padding-top
border-spacing  font padding-right
border-style  font-family padding-bottom
border-top font-size padding-left
border-right  font-size-adjust page-break-after
border-bottom  font-style page-break-before
border-left  font-variant page-break-inside
border-top-color  font-weight position
border-right-color  height quotes
border-bottom-color  left right
border-left-color letter-spacing table-layout
border-top-style line-height text-align
border-right-style list-style text-decoration
border-bottom-style list-style-image text-indent
border-left-style list-style-position text-shadow
border-top-width list-style-type text-transform
border-right-width margin top
border-bottom-width margin-top vertical-align
border-left-width margin-right visibility
border-width margin-bottom white-space
bottom margin-left width
caption-side word-spacing
clear max-height z-index

(D)Other Style Values-


CSS Background properties like background-color, background-
image, background-position, background-repeat, background-
attachment properties and many more.
Here are some CSS Background properties listed with example.

CSS background-color
CSS background-color property set background color.
Example Code:
<body>
<p style="background-color:orange;">This paragraph
background color orange</p>
</body>
Run it...   »
Example Result:
This paragraph background color orange

CSS background-image
CSS background-image property set image in background.
Example Code:
<body>
<p style="background-
image:url(/jix/img_nat.png);color:#FFFFFF;
height:130px;width:200px;font-size:20px">
This example is Background Image set in element.</p>
</body>
Run it...   »
Example Result:
This example is Background Image set in element.
CSS background-repeat
CSS background-repeat property repeat image both side horizontaly
or varticaly. CSS background-repeat property posible value is repeat,
no-repeat, repeat-x (verticaly repeat), and repeat-y (horizontaly
repeat).
Example Code:
<body>
<p style="background-
image:url(/jix/img_nat.png);height:120px; background-repeat:no-
repeat;">This example is Background repeat.</p>
</body>
Run it...   »
Example Result:
This example is Background repeat.

CSS background-attachment
CSS background-attachment property use to set background image in
different type attachment like fixed, scroll.
Example Code:
<body>
<p style="background-
image:url(/jix/img_nat.png);height:130px;width:200px;overflow:scrol
l;background-attachment:fixed;color:white;">This example is
Background attachment image is fixed
means image does not moved only fixed attached a image.
background attachment posible value fixed or scroll. you can use this
value and display results.This example is Background attachment
image is fixed means image does not moved only fixed attached
a image. background attachment posible value fixed or scroll. you can
use this value and display results.</p>
</body>
Run it...   »
Example Result:
This example is Background attachment image is fixed means image
does not moved only fixed attached a image. background attachment
posible value fixed or scroll. you can use this value and display
results.This example is Background attachment image is fixed means
image does not moved only fixed attached a image. background
attachment posible value fixed or scroll. you can use this value and
display results.
CSS background-position
CSS background-position property use to set background image in
different type position like left, right, center, top, bottom.
Example Code:
<body>
<p style="background-
image:url(/jix/img_nat.png);height:120px;background-repeat:no-
repeat;background-position:150px;"> This example is Background
Position left 150 pixel.</p>
</body>
Run it...   »
Example Result:
This example is Background Position left 150 pixel.

Style sheet

1. In-Line Style Sheet


Inline CSS Style write in element line using style attribute. All most
every html element support style attribute.
Inline stylesheet priority high more than other three.
Inline CSS style consists set of rules in 4 part:

1. Selector (Element)
2. Style (Attribute)
3. Property and
4. Value

How to write Inline CSS Style


Selector is normally HTML element that element you want to assign
CSS style. And style is attribute to assign CSS property and set
suitable value.
Example Code:
<p style="color:purple;margin-left:20px;">This is a paragraph line.
</p>
<div style="color:purple;font-size:16px;background-
color:#FF6633;">This is a paragraph Second line.</p>
Run it...   »
Example Result:

This is a paragraph line.


This is a paragraph Second line.

2. Embedded/internal Style Sheet

Embedded CSS Style includes within webpage using <style


type="text/css">.....</style> element and between this element CSS
style properties are listed. Internal CSS style normally written
within <head>.....</head> element of the webpage.
Internal CSS style consists set of rules in 3 part:

1. Selector (element, class, id)


2. Property and
3. Value

How to write Internal CSS Style


Selector is normally HTML element that element you want to assign
CSS style. All elements within webpage that elements assign CSS
properties and set suitable values.
Example Code:
<html>
<head>
<style type="text/css">
p{
color:purple;
margin-left:20px;
}
div{
color:purple;
font-size:16px;
background-color:#FF6633;
}
</style>
</head>
<body>
<p>This is a paragraph line.</p>
<div>This is a paragraph Second line.</div>
</body>
<html>
Run it...   »
Example Result:

This is a paragraph line.


This is a paragraph Second line.

3. External Style Sheet

External Style Sheet define in separate .css extension file. and used to


make global change also manage all webpage from a single CSS
document.
External style sheets give you control to change formatting and layout
styles of every single elements in webpages. And only those webpage
who are linked with external CSS document.
External style sheet consists set of rules in 4 part:

1. External Source link


2. Selector (element, class, id)
3. Property and
4. Value

How to write External Stylesheet


External stylesheet linked to a webpage.
Selector is normally HTML element (or class, id) to assign CSS
properties and set suitable values.
Example Code:
jnj_css.css
/*CSS Style*/
p{
color:purple;
margin-left:20px;
}
div{
color:purple;
font-size:16px;
background-color:#FF6633;
}
<head>
<link rel="stylesheet" type="text/css" href="jnj_css.css" />
</head>
<body>
<p>This is a paragraph line.</p>
<div>This is a paragraph Second line.</div>
</body>
Run it...   »
Example Result:

This is a paragraph line.


This is a paragraph Second line.
(E)Grouping

 In group sections of an HTML page when you want to perform an


action on multiple elements.
 For example, you might group a series of paragraphs in order to
apply a single style to the entire section, instead of to each
paragraph individually.
 You use the HTML tags DIV and SPAN to group your elements
in this way:

 DIV is used to group a series of elements into a larger group. For


example, you can group multiple paragraphs and headings or
several elements on a form together using the DIV tag. DIV is used
to offset a group of elements; that is, when you insert a DIV tag in
a page, the DIV tag adds a paragraph break after its closing tag.
DIV should not be used within a paragraph of text for this reason.
 SPAN is used within an element to group a part of it that is too
small to capture with regular HTML tags. For example, you can
use the SPAN tag to group a few sentences from within a
paragraph, so you can perform actions that affect only that text.
SPAN does not make formatting changes to the document as does
the DIV tag, and is therefore better suited for use within
paragraphs and in other elements where you do not want to
introduce more white space.
 You can add DIV and SPAN tags to the page designer by
highlighting the elements you want to group, then choosing the
DIV or SPAN icon from the toolbar. Visual Basic automatically
inserts the appropriate opening and closing tags in the HTML for
your page. The resulting DIV and SPAN elements appear in the
tree view, and you can assign IDs and write code for them.

 Grouping elements in DIV and SPAN tags can be an important


part of your coding efforts, because it allows you to manipulate
precise portions of the page. The following HTML code shows an
example of DIV and
SPAN tags used to manipulate parts of a Web page:

<DIV id="client-fullname" class="client">


<SPAN class="client-lastname">Last name:</SPAN>
<SPAN class="client-firstname">First name:</SPAN>
</DIV>
In this example, a DIV tag with the ID "client-fullname" groups the
fields that specify the client's first and last name. Each label is part of a
SPAN tag. If you wanted to perform an operation on all of the fields on
the form, you could use the DIV tag to do so. If you wanted to perform
an operation on just one item in the form, you could use the appropriate
SPAN tag.

To add a DIV or SPAN tag to your page

1. Select the elements on your HTML page that you want to enclose
in a DIV or SPAN tag.

Note   You can highlight the elements in either the drawing surface


or in the treeview.

2. Click the Wrap Selection in <DIV>…</DIV> toolbar icon to add


a DIV tag, or the Wrap Selection in <SPAN>…</SPAN> toolbar
icon to add a SPAN tag.

Visual Basic inserts opening and closing tags around your


selection.

3. If you want to program the DIV or SPAN elements, add a unique


ID for each element by selecting it in the treeview panel, then
setting its ID property in the Properties window.
(F) Inheritance

1. Inheritance is a way to reuse code of existing objects, or to create


an object using the other object.
What do I mean by creating an object from another object?

Yes, It's like parent and child... Real world example : your parent
created you, and you inherit some of their appearance or behaviors
(Silly but true..)

It's also the same in Inheritance.. there is a parent CLASS and a


child CLASS
we are going to call the parent class "Superclass" and the child
class "Subclass"

take a look at this and understand

In the image above I have a SuperClass Car with 2


SubClass Racecar and Truck 

2. A car has generic features that every car has.. for example the
Color, horsepower and #of seats... we can also use the tire..
because every car has this properties, and there are some properties
that is specific to a given car... for example the Racecar.
3. it has nitro while truck doesn't have.. Truck have trailer while
Racecar doesn't have.. right? In that case we are going to write
those attributes in each subclass, not in the Superclass..
4. In traditional way of coding.. think that we are making a Car
driving game and we have this classes, without Inheritance we are
going to create different classes and give those classes their
attributes.. it's like we are retyping the same code all over again for
all the same attributes.
5. so why not create a class that would share properties into each of
the Cars?

<html>
<head>
<title>Inheritance</title>
<script type="text/javascript">
function Song(title,type) {
this.title = title;
this.type = type;
this.getTitle=function() {
return "Song: " + this.title + " Type: " + this.type;
}
}

function SubSong(title,type,artist) {
this.artist = artist;
this.toString("Artist is " + artist);
Song.apply(this,arguments);
this.toString = function () {
return "Artist: " + this.artist + " " + this.getTitle();
}
}
SubSong.prototype = new Song();

var song = new SubSong("name", "type", "Artist");


alert(song.toString());
</script>

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

(G)Classes as Selector

In an HTML document, CSS class selectors match an element based on


the contents of the element's class attribute. The class attribute is defined
as a space-separated list of items, and one of those items must match
exactly the class name given in the selector.
Syntax
How to read CSS syntax.
.classname { style properties }
Note this is equivalent to the following attribute selector:
How to read CSS syntax.
[class~=classname] { style properties }
Example
CSS
span.classy {
background-color: DodgerBlue;
}
HTML
<span class="classy">Here's a span with some text.</span>
<span>Here's another.</span>
(H)ID as Selector

In an HTML document, CSS ID selectors match an element based on the


contents of that element's id attribute, which must match exactly the
value given in the selector.
Syntax
How to read CSS syntax.
#id_value { style properties }
Note this is equivalent to the following attribute selector:
How to read CSS syntax.
[id=id_value] { style properties }

Example
span#identified {
background-color: DodgerBlue;
}
<span id="identified">Here's a span with some text.</span>
<span>Here's another.</span>
(I)Contextual Selector

 The first part of a style rule is the selector.


 Selector as we have mentioned above selects the
elements <tags> to which the style rule properties will be
applied.
 In the previous section we saw how we used classes to apply a
style to specific HTML elements.
 Another way to set styles to a certain element is to indicate that
the rules apply only when that element is within another type of
element.
 The selector contains a list of one or more tag names, separated
by spaces.
 The rule is applied to every tag in the HTML document without
regard to position or tag nesting.
 With this type of selector, called a contextual selector,  we can
put the name of the outer element, then a space, then the name of
the inner element and have some control over the styles applied
to tags in a specific order in our web document.
 A well-formed HTML document is created by nested tags,
starting with the outer <html> and continue in
the <body> section with paragraphs, frames, tables, divisions,
and other flow control elements, which enclose the document
content.
 Keep in mind that you have to build your web documents as a
tag nesting within tags.

Look at the following example:


<style><!-- which gives us
h2  a
      {font-style:italic;  
}
--></style>
 
  New e-books, August 2006
We then write the HTML code as below:
<h1>New e-books,  
    <a  href="August.html">August 2006</a>
</h1>
 
 
 Using contextual selectors, you declare style properties that are
only applied when certain tags are nested within other tags.
 Let's create a contextual selector that causes all text with table
cells to be red and smaller than the rest of our document:
The contextual selectors rule is the following:
 
table  tr  td  p { font-size : 10pt; color: red 
}
table p  { font-size : 12px; color: gray 

 
 In the  first rule syntax above we followed the complete sequence
of nested tags that needs the HTML structure hierarchy.
 This means that the outer element as selector must be the table
and tr, td and p the inner elements. When the browser reads this
nesting sequence, it will apply the font-size : smaller  and color
properties to the text content.
 The second CSS rule will apply the style for <p> tag nested
somewhere within a <table>tag in the document, regardless of
intermediate tags between them.

Let us write the HTML code to apply the previous style rules:
 
Document  Contextual_selectors.html:
 
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
   <title>Contextual selectors</title>
   <meta name="Author" content="A. Gklinos" />
   <meta http-equiv="Content-Language" content="en" />
<style><!--
 table tr td {font-size : 10pt; color: red 
 }
 table a { font-size : 12pt; font-style:italic
 } 
--></style>
</head>
<body>
 <table border="1">
  <caption>
   <a href="http://www.w3opensource.com/outer.html">outer
elements</a>
  </caption>
  <tr><td width="100%">The outer element as selector</td></tr>
 </table>
 <br />
 <table border="1">
  <caption>
   <a href="http://www.w3opensource.com/inner.html">inner
elements</a>
  </caption>
  <tr>
   <td>The inner elements must have as parent the outer
element</td>
  </tr>
 </table>
</body>
</html>

 
Running this document with Firefox  you will get the following
screen.
 

 
 
 
Contextual selectors with Classes
 
 Contextual selectors can also be used with classes.
You can create contextual selectors with classes to further control
your web documents styles.
 In the following example we create a CSS rule with the class
selector as the element div and contextual selector as the element
h3.
 
div . italic  h3 {font-style: italic}

If we want for the <div ...> element the text to be larger than usual,


and its anchors content to be italic, we create two more style rules,
one with a general class for the font size and another for the italic
font style as a class with a  contextual selector,  as follows:
 
. Lsize     { font-size:150%;
}
. Lsize  a  { font-style:italic;
}
 
The first declaration rule says that all Lsize elements will have a font
size of 140% and the second rule says that the content
of <a ...> elements within Lsize elements will be italic.
To apply the above style to a <div ...> element we join the above
three style rules in a CSS style sheet and embed it into the following
HTML document.
 
 Document  Contextual_selectors_with_classes.html :  
 
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
   <title>Contextual selectors with Classes</title>
   <meta name="Author" content="A. Gklinos" />
   <meta http-equiv="Content-Language" content="en" />
<style>
<!--
div.italic h3 {font-style: italic;
 } 
.Lsize   {font-size:130%;
}
.Lsize a {font-style:italic;
}
--></style>
</head>

<body>
    <div class="italic">
       <h3>Contextual selectors with Classes</h3>
   </div>
   <div class="Lsize">
       Contextual selectors can also be used in conjunction with
classes.
      <a
href="http://www.w3opensource.com/selectors_classes.html">
          Contextual selectors with Classes</a>
  </div>
</body>
</html>

Running this document with Firefox  you will get the following
screen.
 

 
 The style rule and the value of the style property for a contextual
selector concern always the child element and never the parent or
ancestor element.
 The contextual selector differs from the generic selector because
the first contains one or more parent elements.
 In case we declared a style rule with a contextual selector to set a
value for a property of an element and through a generic selector
we have created a rule that sets value for another property of the
same element, then the setting of the contextual selector will be
done first as a more specific declaration for the element.
 The contextual selectors can be defined with simple element
names, names of classes, id names or as a combination of them.
 
Grouping Contextual selectors
 
 We can create groups of contextual selectors,
but our reference must follow the sequence of nested tags that the
HTML structure needs as we have mentioned previously.
 Each group of contextual selectors is separated from the others
by comma (,).
Look at the following example:
 h2  b,  h3  b, p  em,  p  i  { color: blue } 

This shows that you have to follow the hierarchic structure of the
HTML elements for each group of contextual selectors. You might
want to use the separate syntax for the  declaration above. In this
case you could write analytically in separate style rules the previous
grouped style rule,  as below: 
 
 h2  b  { color: blue 
 }
 h3  b  { color: blue
 }
 p  em  { color: blue
 }
 p  i      { color: blue
 }
Now your HTML is simpler and  it is clear that the CSS follows the
HTML structure.
(J)Pseudo Classes and Pseudo Elements

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

 Style an element when a user mouses over it


 Style visited and unvisited links differently
 Style an element when it gets focus

Mouse Over Me

Syntax

The syntax of pseudo-classes:

selector:pseudo-class {
    property:value;
}

Anchor Pseudo-classes

Links can be displayed in different ways:

Example
/* unvisited link */
a:link {
    color: #FF0000;
}

/* visited link */
a:visited {
    color: #00FF00;
}

/* mouse over link */


a:hover {
    color: #FF00FF;
}

/* selected link */
a:active {
    color: #0000FF;
}

Note: a:hover MUST come after a:link and a:visited in the CSS


definition in order to be effective! a:activeMUST come after a:hover in
the CSS definition in order to be effective! Pseudo-class names are not
case-sensitive.

Pseudo-classes and CSS Classes

Pseudo-classes can be combined with CSS classes:

When you hover over the link in the example, it will change color:

Example
a.highlight:hover {
    color: #ff0000;
}

Hover on <div>

An example of using the :hover pseudo-class on a <div> element:


Example
div:hover {
    background-color: blue;
}

Simple Tooltip Hover

Hover over a <div> element to show a <p> element (like a tooltip):

Hover over me to show the <p> element.


Example
p {
    display: none;
    background-color: yellow;
    padding: 20px;
}

div:hover p {
    display: block;
}
CSS - The :first-child Pseudo-class

The :first-child pseudo-class matches a specified element that is the first


child of another element.

Match the first <p> element

In the following example, the selector matches any <p> element that is
the first child of any element:

Example
p:first-child {
    color: blue;
}
Match the first <i> element in all <p> elements

In the following example, the selector matches the first <i> element in
all <p> elements:

Example
p i:first-child {
    color: blue;
}

Match all <i> elements in all first child <p> elements

In the following example, the selector matches all <i> elements in <p>
elements that are the first child of another element:

Example
p:first-child i {
    color: blue;
}

CSS - The :lang Pseudo-class

The :lang pseudo-class allows you to define special rules for different


languages.

In the example below, :lang defines the quotation marks for <q>


elements with lang="no":

Example
<html>
<head>
<style>
q:lang(no) {
    quotes: "~" "~";
}
</style>
</head>

<body>
<p>Some text <q lang="no">A quote in a paragraph</q> Some
text.</p>
</body>
</html>
All CSS Pseudo Classes

Selector Example Example description

:active a:active Selects the active link

:checked input:checked Selects every checked <input> element

:disabled input:disabled Selects every disabled <input> element

:empty p:empty Selects every <p> element that has no

children

:enabled input:enabled Selects every enabled <input> element

:first-child p:first-child Selects every <p> elements that is the

first child of its parent


:first-of-type p:first-of-type Selects every <p> element that is the

first <p> element of its parent

:focus input:focus Selects the <input> element that has

focus

:hover a:hover Selects links on mouse over

:in-range input:in-range Selects <input> elements with a value

within a specified range

:invalid input:invalid Selects all <input> elements with an

invalid value

:lang(language) p:lang(it) Selects every <p> element with a lang

attribute value starting with "it"

:last-child p:last-child Selects every <p> elements that is the

last child of its parent

:last-of-type p:last-of-type Selects every <p> element that is the

last <p> element of its parent


:link a:link Selects all unvisited links

:not(selector) :not(p) Selects every element that is not a <p>

element

:nth-child(n) p:nth-child(2) Selects every <p> element that is the

second child of its parent

:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the

second child of its parent, counting

from the last child

:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the

second <p> element of its parent,

counting from the last child

:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the

second <p> element of its parent

:only-of-type p:only-of-type Selects every <p> element that is the

only <p> element of its parent


:only-child p:only-child Selects every <p> element that is the

only child of its parent

:optional input:optional Selects <input> elements with no

"required" attribute

:out-of-range input:out-of-range Selects <input> elements with a value

outside a specified range

:read-only input:read-only Selects <input> elements with a

"readonly" attribute specified

:read-write input:read-write Selects <input> elements with no

"readonly" attribute

:required input:required Selects <input> elements with a

"required" attribute specified

:root root Selects the document's root element

:target #news:target Selects the current active #news

element (clicked on a URL containing


that anchor name)

:valid input:valid Selects all <input> elements with a

valid value

:visited a:visited Selects all visited links

All CSS Pseudo Elements

Selector Example Example description

::after p::after Insert content after every <p> element

::before p::before Insert content before every <p> element

::first-letter p::first-letter Selects the first letter of every <p>

element

::first-line p::first-line Selects the first line of every <p>

element

::selection p::selection Selects the portion of an element that is

selected by a user
What are Pseudo-Elements?

A CSS pseudo-element is used to style specified parts of an element.

For example, it can be used to:

 Style the first letter, or line, of an element


 Insert content before, or after, the content of an element

Syntax

The syntax of pseudo-elements:

selector::pseudo-element {
    property:value;
}

Notice the double colon notation - ::first-line versus :first-line

The double colon replaced the single-colon notation for pseudo-elements


in CSS3. This was an attempt from W3C to distinguish between pseudo-
classes and pseudo-elements.

The single-colon syntax was used for both pseudo-classes and pseudo-
elements in CSS2 and CSS1.

For backward compatibility, the single-colon syntax is acceptable for


CSS2 and CSS1 pseudo-elements.

The ::first-line Pseudo-element

The ::first-line pseudo-element is used to add a special style to the first


line of a text.

The following example formats the first line of the text in all <p>
elements:
Example 
p::first-line {
    color: #ff0000;
    font-variant: small-caps;
}

Note: The ::first-line pseudo-element can only be applied to block-level


elements.

The following properties apply to the ::first-line pseudo-element:

 font properties
 color properties
 background properties
 word-spacing
 letter-spacing
 text-decoration
 vertical-align
 text-transform
 line-height
 clear

The ::first-letter Pseudo-element

The ::first-letter pseudo-element is used to add a special style to the first


letter of a text.

The following example formats the first letter of the text in all <p>
elements: 

Example
p::first-letter {
    color: #ff0000;
    font-size: xx-large;
}
Note: The ::first-letter pseudo-element can only be applied to block-
level elements.

The following properties apply to the ::first-letter pseudo- element: 

 font properties
 color properties 
 background properties
 margin properties
 padding properties
 border properties
 text-decoration
 vertical-align (only if "float" is "none")
 text-transform
 line-height
 float
 clear

Pseudo-elements and CSS Classes

Pseudo-elements can be combined with CSS classes: 

Example
p.intro::first-letter {
    color: #ff0000;
    font-size:200%;
}

The example above will display the first letter of paragraphs with
class="intro", in red and in a larger size.

Multiple Pseudo-elements

Several pseudo-elements can also be combined.


In the following example, the first letter of a paragraph will be red, in an
xx-large font size. The rest of the first line will be blue, and in small-
caps. The rest of the paragraph will be the default font size and color:

Example
p::first-letter {
    color: #ff0000;
    font-size: xx-large;
}

p::first-line {
    color: #0000ff;
    font-variant: small-caps;
}

CSS - The ::before Pseudo-element

The ::before pseudo-element can be used to insert some content before


the content of an element.

The following example inserts an image before the content of each <h1>
element:

Example
h1::before {
    content: url(smiley.gif);
}

CSS - The ::after Pseudo-element

The ::after pseudo-element can be used to insert some content after the


content of an element.

The following example inserts an image after the content of each <h1>
element:
Example
h1::after {
    content: url(smiley.gif);
}
CSS - The ::selection Pseudo-element

The ::selection pseudo-element matches the portion of an element that is


selected by a user.

The following CSS properties can be applied


to ::selection: color, background, cursor, and outline.

The following example makes the selected text red on a yellow


background:

Example
::selection {
    color: red; 
    background: yellow;
}
All CSS Pseudo Elements

Selector Example Example description

::after p::after Insert something after the content of each

<p> element

::before p::before Insert something before the content of

each <p> element

::first-letter p::first-letter Selects the first letter of each <p>


element

::first-line p::first-line Selects the first line of each <p> element

::selection p::selection Selects the portion of an element that is

selected by a user

All CSS Pseudo Classes

Selector Example Example description

:active a:active Selects the active link

:checked input:checked Selects every checked <input> element

:disabled input:disabled Selects every disabled <input> element

:empty p:empty Selects every <p> element that has no

children

:enabled input:enabled Selects every enabled <input> element

:first-child p:first-child Selects every <p> elements that is the


first child of its parent

:first-of-type p:first-of-type Selects every <p> element that is the

first <p> element of its parent

:focus input:focus Selects the <input> element that has

focus

:hover a:hover Selects links on mouse over

:in-range input:in-range Selects <input> elements with a value

within a specified range

:invalid input:invalid Selects all <input> elements with an

invalid value

:lang(language) p:lang(it) Selects every <p> element with a lang

attribute value starting with "it"

:last-child p:last-child Selects every <p> elements that is the

last child of its parent


:last-of-type p:last-of-type Selects every <p> element that is the

last <p> element of its parent

:link a:link Selects all unvisited links

:not(selector) :not(p) Selects every element that is not a <p>

element

:nth-child(n) p:nth-child(2) Selects every <p> element that is the

second child of its parent

:nth-last-child(n) p:nth-last-child(2) Selects every <p> element that is the

second child of its parent, counting

from the last child

:nth-last-of-type(n) p:nth-last-of-type(2) Selects every <p> element that is the

second <p> element of its parent,

counting from the last child

:nth-of-type(n) p:nth-of-type(2) Selects every <p> element that is the

second <p> element of its parent


:only-of-type p:only-of-type Selects every <p> element that is the

only <p> element of its parent

:only-child p:only-child Selects every <p> element that is the

only child of its parent

:optional input:optional Selects <input> elements with no

"required" attribute

:out-of-range input:out-of-range Selects <input> elements with a

value outside a specified range

:read-only input:read-only Selects <input> elements with a

"readonly" attribute specified

:read-write input:read-write Selects <input> elements with no

"readonly" attribute

:required input:required Selects <input> elements with a

"required" attribute specified

:root root Selects the document's root element


:target #news:target Selects the current active #news elemen
containing that anchor name)

:valid input:valid Selects all <input> elements with

valid value

:visited a:visited Selects all visited links

(K)Positioning

The position property specifies the type of positioning method used for


an element (static, relative, fixed or absolute).

The position Property

The position property specifies the type of positioning method used for


an element.
There are four different position values:

 static
 relative
 fixed
 absolute

Elements are then positioned using the top, bottom, left, and right
properties. However, these properties will not work unless
the position property is set first. They also work differently depending
on the position value.

position: static;

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and
right properties.

An element with position: static; is not positioned in any special way; it


is always positioned according to the normal flow of the page:

This <div> element has position: static;

Here is the CSS that is used:

Example
div.static {
    position: static;
    border: 3px solid #73AD21;
}

position: relative;

An element with position: relative; is positioned relative to its normal


position.

Setting the top, right, bottom, and left properties of a relatively-


positioned element will cause it to be adjusted away from its normal
position. Other content will not be adjusted to fit into any gap left by the
element.

This <div> element has position: relative;

Here is the CSS that is used:

Example
div.relative {
    position: relative;
    left: 30px;
    border: 3px solid #73AD21;
}

position: fixed;

An element with position: fixed; is positioned relative to the viewport,


which means it always stays in the same place even if the page is
scrolled. The top, right, bottom, and left properties are used to position
the element.

A fixed element does not leave a gap in the page where it would
normally have been located.

Notice the fixed element in the lower-right corner of the page. Here is
the CSS that is used:

Example
div.fixed {
    position: fixed;
    bottom: 0;
    right: 0;
    width: 300px;
    border: 3px solid #73AD21;
}
This <div> element has position: fixed;
position: absolute;

An element with position: absolute; is positioned relative to the nearest


positioned ancestor (instead of positioned relative to the viewport, like
fixed).

However; if an absolute positioned element has no positioned ancestors,


it uses the document body, and moves along with page scrolling.

Note: A "positioned" element is one whose position is anything


except static.

Here is a simple example:

This <div> element has position: relative;


This <div> element has position: absolute;

Here is the CSS that is used:

Example
div.relative {
    position: relative;
    width: 400px;
    height: 200px;
    border: 3px solid #73AD21;

div.absolute {
    position: absolute;
    top: 80px;
    right: 0;
    width: 200px;
    height: 100px;
    border: 3px solid #73AD21;
}
Overlapping Elements

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which


element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

This is a heading

Because the image has a z-index of -1, it will be placed behind the text.

Example
img {
    position: absolute;
    left: 0px;
    top: 0px;
    z-index: -1;
}

An element with greater stack order is always in front of an element with


a lower stack order.

Note: If two positioned elements overlap without a z-index specified,


the element positioned last in the HTML code will be shown on top.

Positioning Text In an Image

How to position text over an image:


Example

Bottom Left Top Left Top Right Bottom Right

All CSS Positioning Properties

Property Description

bottom Sets the bottom margin edge for a positioned box

clip Clips an absolutely positioned element

cursor Specifies the type of cursor to be displayed

left Sets the left margin edge for a positioned box

overflow Specifies what happens if content overflows an


element's box

overflow-x Specifies what to do with the left/right edges of the

Content if it overflows the element's content area

overflow-y Specifies what to do with the top/bottom edges of the

content if it overflows the element's content area

position Specifies the type of positioning for an element

right Sets the right margin edge for a positioned box

top Sets the top margin edge for a positioned box

z-index Sets the stack order of an element

(L)Backgrounds

The CSS background properties are used to define the


background effects for elements.

CSS background properties:

 background-color
 background-image
 background-repeat
 background-attachment
 background-position

Background Color

The background-color property specifies the background color of an


element.

The background color of a page is set like this:

Example
body {
    background-color: lightblue;
}

With CSS, a color is most often specified by:

 a valid color name - like "red"


 a HEX value - like "#ff0000"
 an RGB value - like "rgb(255,0,0)"

Look at CSS Color Values for a complete list of possible color values.

In the example below, the <h1>, <p>, and <div> elements have different
background colors:

Example
h1 {
    background-color: green;
}

div {
    background-color: lightblue;
}
p {
    background-color: yellow;
}

Background Image

The background-image property specifies an image to use as the


background of an element.

By default, the image is repeated so it covers the entire element.

The background image for a page can be set like this:

Example
body {
    background-image: url("paper.gif");
}

Below is an example of a bad combination of text and background


image. The text is hardly readable:

Example
body {
    background-image: url("bgdesert.jpg");
}

Note: When using a background image, use an image that does not


disturb the text.

Background Image - Repeat Horizontally or Vertically

By default, the background-image property repeats an image both


horizontally and vertically.
Some images should be repeated only horizontally or vertically, or they
will look strange, like this:

Example
body {
    background-image: url("gradient_bg.png");
}

If the image above is repeated only horizontally (background-repeat:


repeat-x;), the background will look better:

Example
body {
    background-image: url("gradient_bg.png");
    background-repeat: repeat-x;
}

Tip: To repeat an image vertically, set background-repeat: repeat-y;

Background Image - Set position and no-repeat

Showing the background image only once is also specified by


the background-repeat property:

Example
body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
}
In the example above, the background image is shown in the same place
as the text. We want to change the position of the image, so that it does
not disturb the text too much.

The position of the image is specified by the background-


position property:

Example
body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
    background-position: right top;
}

Background Image - Fixed position

To specify that the background image should be fixed (will not scroll
with the rest of the page), use the background-attachment property:

Example
body {
    background-image: url("img_tree.png");
    background-repeat: no-repeat;
    background-position: right top;
    background-attachment: fixed;
}

Background - Shorthand property

To shorten the code, it is also possible to specify all the background


properties in one single property. This is called a shorthand property.

The shorthand property for background is background:


Example
body {
    background: #ffffff url("img_tree.png") no-repeat right top;
}

When using the shorthand property the order of the property values is:

 background-color
 background-image
 background-repeat
 background-attachment
 background-position

It does not matter if one of the property values is missing, as long as the
other ones are in this order.

All CSS Background Properties

Property Description
background Sets all the background properties in one declaration

background-attachment Sets whether a background image is fixed or scrolls

with the rest of the page

background-color Sets the background color of an element

background-image Sets the background image for an element

background-position Sets the starting position of a background image

background-repeat Sets how a background image will be repeated

(M)Element Dimensions
CSS Layout - Horizontal & Vertical Align
In CSS, several properties can be used to align elements horizontally
and vertically.
Center Align Elements

To horizontally center a block element (like <div>), use margin: auto;

Setting the width of the element will prevent it from stretching out to the
edges of its container.

The element will then take up the specified width, and the remaining
space will be split equally between the two margins:

This div element is centered.

Example
.center {
    margin: auto;
    width: 50%;
    border: 3px solid green;
    padding: 10px;
}

Note: Center aligning has no effect if the width property is not set (or set


to 100%).

Center Align Text

To just center the text inside an element, use text-align: center;

This text is centered.

Example
.center {
    text-align: center;
    border: 3px solid green;
}

Tip: For more examples on how to align text, see the CSS Text chapter.

Center an Image

To center an image, use margin: auto; and make it into a block element:

Example
img {
    display: block;
    margin: auto;
    width: 40%;
}

Left and Right Align - Using position

One method for aligning elements is to use position: absolute;:


In my younger and more vulnerable years my father gave me some
advice that I've been turning over in my mind ever since.

Example
.right {
    position: absolute;
    right: 0px;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

Note: Absolute positioned elements are removed from the normal flow,


and can overlap elements.

Tip: When aligning elements with position, always


define margin and padding for the <body> element. This is to avoid
visual differences in different browsers.

There is also a problem with IE8 and earlier, when using position. If a


container element (in our case <div class="container">) has a specified
width, and the !DOCTYPE declaration is missing, IE8 and earlier
versions will add a 17px margin on the right side. This seems to be space
reserved for a scrollbar. So, always set the !DOCTYPE declaration when
using position:

Example
body {
    margin: 0;
    padding: 0;
}

.container {
    position: relative;
    width: 100%;
}
.right {
    position: absolute;
    right: 0px;
    width: 300px;
    background-color: #b0e0e6;
}

Left and Right Align - Using float

Another method for aligning elements is to use the float property:

Example
.right {
    float: right;
    width: 300px;
    border: 3px solid #73AD21;
    padding: 10px;
}

Tip: When aligning elements with float, always


define margin and padding for the <body> element. This is to avoid
visual differences in different browsers.

There is also a problem with IE8 and earlier, when using float. If the !
DOCTYPE declaration is missing, IE8 and earlier versions will add a
17px margin on the right side. This seems to be space reserved for a
scrollbar. So, always set the !DOCTYPE declaration when using float:

Example
body {
    margin: 0;
    padding: 0;
}

.right {
    float: right;
    width: 300px;
    background-color: #b0e0e6;
}

Center Vertically - Using padding

There are many ways to center an element vertically in CSS. A simple


solution is to use top and bottom padding:

I am vertically centered.

Example
.center {
    padding: 70px 0;
    border: 3px solid green;
}

To center both vertically and horizontally, use padding and text-align:


center:

I am vertically and horizontally centered.

Example
.center {
    padding: 70px 0;
    border: 3px solid green;
    text-align: center;
}
Center Vertically - Using line-height

Another trick is to use the line-height property with a value that is equal


to the height property.

I am vertically and horizontally centered.

Example
.center {
    line-height: 200px;
    height: 200px;
    border: 3px solid green;
    text-align: center;
}

/* If the text has multiple lines, add the following: */


.center p {
    line-height: 1.5;
    display: inline-block;
    vertical-align: middle;
}

Center Vertically - Using position & transform

If padding and line-height is not an option, a third solution is to use


positioning and the transform property:

I am vertically and horizontally centered.

Example
.center { 
    height: 200px;
    position: relative;
    border: 3px solid green; 
}
.center p {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
DHTML Document Object Model and Collections

As of December 2011, this topic has been archived and is no longer


actively maintained. For more information, see Archived Content. For
information, recommendations, and guidance regarding the current
version of Windows Internet Explorer, see Internet Explorer Developer
Center.
 The Dynamic HTML (DHTML) Document Object Model (DOM)
allows authors direct, programmable access to the individual
components of their Web documents, from individual elements to
containers. This access, combined with the event model, allows the
browser to react to user input, execute scripts on the fly, and display the
new content without downloading additional documents from a server.
The DHTML DOM puts sophisticated interactivity within easy reach of
the average HTML author.

 What Is the Object Model?


 Accessing Elements with Script
 Events: Bubbling, Canceling, and Handling
 Handling Rollover Effects
 Canceling Events
 Special Considerations
 Related topics

What Is the Object Model?

 The object model is the mechanism that makes DHTML


programmable.
 It doesn't require that authors learn new HTML tags, and it doesn't
involve any new authoring technologies. In fact, the object model
builds on functionality that authors have used to create content for
previous browsers. Remember setting the value for a form element
in script, or adding on mouse over events to links in Microsoft
Internet Explorer 3.0?
 If so, you've been using a limited form of the object model to
access your HTML with script.
 What's different in the current object model is that now every
HTML element is programmable. This means every HTML
element on the page can have script behind it that can be used to
interact with user actions and change the page content
dynamically.
 This event model lets a document react when the user has done
something on the page, such as moving the mouse pointer over a
particular element, pressing a key, or entering information into a
form input.
 Each event can be linked to a script that tells the browser to
modify the content on the fly, without having to go back to the
server for a new file.
 The advantages to this are that authors will be able to create
interactive Web sites with fewer pages, and users do not have to
wait for new pages to download from Web servers, increasing the
speed of their browsing and the performance of the Internet as a
whole.
Accessing Elements with Script

 Every HTML element is a scriptable object in the object model,


with its own set of properties, methods, and events. However, to
write script for each element object, the author must know how to
get to an element.
 The object model focuses on collections of elements, a hierarchy
of groupings that the elements fall into. The most important of
these collections are the all collection and the children collection.
A DHTML document is a structured arrangement of elements, and
in the following example, each element has a scope of influence
that depends on where in the document the tags appear.

<HTML>
<BODY>
<DIV>
<P>Some text in a
<B>paragraph</B>
</P>
<IMG id=image1 src="mygif.gif">
</DIV>
<IMG id=image2 src="mygif.gif">
</BODY>
</HTML>

 In the preceding example, the div object contains (and is the parent


of) the p object and the img object called image1. Conversely,
image1 and the p are children of the div. The img object called
image2, however, is a child of the body object.
 Each element object has an all collection that contains all the
elements that are beneath that element in the hierarchy, and
a children collection that contains only the elements that are direct
descendants of that element.
 In the preceding example, the b would be in
the div object's all collection, but would not appear in
the div object's children collection. Similarly, the div is a member
of the body object's children collection, but the p is not.
 In addition to these collections for each element, the document
itself (represented by the document object) has a number of
element and non element collections.
 The most important collection is an all collection that contains all
the elements on the Web page. This collection is the primary way
to access elements through script. For more information about
using collections, see Scripting with Elements and Collections.

(A)Using the Collection all

 As of December 2011, this topic has been archived and is no longer
actively maintained. For more information, see Archived Content. For
information, recommendations, and guidance regarding the current
version of Windows Internet Explorer, see Internet Explorer Developer
Center.
 
This section contains a list of the collections exposed by the Dynamic
HTML (DHTML) Object Model.

Collections
Topic Contents

Returns a reference to the collection of


all elements contained by the object.

anchors Retrieves a collection of all a objects


that have a name and/or id property.
Objects in this collection are in HTML
source order.

applets Retrieves a collection of


all applet objects in the document.

areas Retrieves a collection of


the area objects defined for the
given map object.

attributes Retrieves the collection of attributes


belonging to the object.

behaviorUrns Returns a collection of Uniform


Resource Name (URN) strings
identifying the behaviors attached to the
element.

blockFormats Retrieves a collection of strings that


specify the names of the available block
format tags.

bookmarks Returns a collection of Microsoft


ActiveX Data Objects (ADO)
bookmarks tied to the rows affected by
the current event.

boundElements Returns a collection of all elements on


the page bound to a data set.

cells Retrieves a collection of all cells in the


table row or in the entire table.

childNodes Retrieves a collection of HTML


Elements and TextNode objects that are
direct descendants of the specified
object.

children Retrieves a collection of DHTML


Objects that are direct descendants of
the object.

controlRange A collection of elements returned by


the createControlRange or createRan
ge method.

documentCompatibleInfoCo Retrieves a collection


llection of DocumentCompatibleInfo objects.

elements Retrieves a collection, in source order,


of all controls in a given form. input
type=image objects are excluded from
the collection.

embeds Retrieves a collection of


all embed objects in the document.

filters Retrieves the collection of filters that


have been applied to the object.

fonts Retrieves a collection of all the system-


supported fonts.

forms Retrieves a collection, in source order,


of all form objects in the document.

frames Retrieves a collection of


all window objects defined by the given
document or defined by the document
associated with the given window.
images Retrieves a collection, in source order,
of img objects in the document.

imports Retrieves a collection of all the


imported style sheets defined for the
respective styleSheet object.

links Retrieves a collection of all a objects


that specify the href property and
all area objects in the document.

mimeTypes Not implemented.

namespaces Retrieves a collection


of namespace objects.

options Retrieves a collection of


the option objects in a select object.

pages Retrieves a collection of page objects,


which represent @page rules in
a styleSheet.

plugins Retrieves a collection of


allembedobjects within the document.

rows Retrieves a collection of tr (table row)


objects from a table object.

rules Retrieves a collection of rules defined in


a style sheet.

scripts Retrieves a collection of


all script objects in the document.

StaticNodeList A collection of objects returned by


the querySelectorAll method.

styleSheets Retrieves a collection


of styleSheet objects representing the
style sheets that correspond to each
instance of a link or style object in the
document.

tBodies Retrieves a collection of


all tBody objects in the table. Objects in
this collection are in source order.

TextRange Retrieves a collection


of TextRange objects.

TextRectangle A collection of TextRectangle objects


returned by the getClientRects method.

(B)Moving object around the documents

If you like working with animations, you'll be glad to know that with
DHTML, the entire web page is now your drawing board! You can
create content that fly all over the screen freely. In Netscape, this is done
by manipulating the left and top attributes of the <layer> tag. In IE 4, the
same thing is accomplished by altering the pixelLeft and pixelTop
properties of the style object.

-Moving elements in NS 4

Recall that layers support the left and top property, which controls its
offset from the document's upper left corner. Well, by using simple math
and a couple of lines of script, we can dynamically update these
properties so the layer moves! The below example changes the left
property of a layer so it moves horizontally when a button is pressed.

<layer name="space" left=128>


<img src="TN00018A.gif">
</layer>
<script>
function moving(){
if (document.space.left<1000)
document.space.left+=5
moveid=setTimeout("moving()",50)
}

function come_back(){
clearTimeout(moveid)
document.space.left=128
}
</script>

<form>
<input type="button" value="Move" onClick="moving()">
<input type="button" value="Come back" onClick="come_back()">
</form>

See, all I did was continuously add to the left property of "space" to
move it, and set the property back to its original value when I want the
layer returned back to its initial location.

-Moving elements in IE 4

By the way, the day when NS and IE agree upon one implementation of
DHTML is the day I can stop writing two versions of everything (just
letting out a little frustration). Moving an element in IE 4 involves
basically first wrapping that element either inside a positioned span or
div, then changing the span or div's pixelLeft and pixelTop properties. It
sounds complicated, but is actually very simple:

<div id="spaceship" style="position:relative">
<img src="TN00018A.gif">
</div>
<script>
function moving2(){
if (spaceship.style.pixelLeft<1000)
spaceship.style.pixelLeft+=5
moveid2=setTimeout("moving2()",50)
}

function come_back2(){
clearTimeout(moveid2)
spaceship.style.pixelLeft=0
}
</script>

<form>
<input type="button" value="Move" onClick="moving2()">
<input type="button" value="Come back" onClick="come_back2()">
</form>

What I did first was set the outside <div> called "spaceship" to a
position of relative, which is necessary to make the element movable
(you could also set it to a value of "absolute"). Then, by manipulating
the pixelWidth property of it's style object, the element moves.
Event Handling
(A)Assigning Event Handlers

 Event handling has been part of JavaScript since the language's


inception. As described in our event handler tutorial, they refer to
specific, user imitated actions within the webpage, such as the
moving of your mouse over a link, the clicking on a link, or
submission of a form.

 Thanks to event handling, our scripts are more interactive and are
able to perform certain actions depending on the user's.

 The DOM of modern web browsers such as IE5+, NS6+, and


Firefox provide expanded methods and flexibility (relative to older
browsers) for capturing events. In this tutorial, we explore event
handling in the DOM, and the differing support for it in IE5+ and
NS6+/Firefox.

The 2 traditional ways of assigning event handlers

Let's first review (for most of us, at least) the 2 common and
conventional ways of setting up an event handler- via HTML, or
scripting. In both cases, a function or code is attached at the end, which
is executed when the handler detects the specified event.

1) Via HTML, using attributes

We can define an event handler directly inside the relevant HTML tag,
by embedding it as a attribute. A piece of JavaScript is also included to
tell the browser to perform something when the event occurs. For
example,

<a href="http://freewarejava.com" onMouseover="window.status='Click


here for Java applets';return true"
onMouseout="window.status=''">Freewarejava.com</a>

Demo:
Freewarejava.com

Here the event handler (onMouseover) is directly added inside the


desired element (A), along with the JavaScript to execute.

2) Via scripting

You can also assign and set up event handlers to elements using
scripting, and inside your script . This allows for the event handlers to be
dynamically set up, without having to mess around with the HTML
codes on the page.

When setting up event handlers for an element directly inside your


script, the code to execute for the events must be defined inside a
function. Just look at the below, which does the same thing as above, but
with the event handler defined using scripting:

<a ID="test" href="http://freewarejava.com">Freewarejava.com</a>


<script type="text/javascript">
 function changestatus(){
window.status="Click here for Java applets"
return true
}
 function changebackstatus(){
window.status=''
}
 document.getElementById("test").onmouseover=changestatus
document.getElementById("test").onmouseout=changebackstatus
 </script>
(B)Even Bubbling

Event bubbling simply passes these unhandled events to the parent


element for handling. The event continues up ("bubbles up") the element
hierarchy until it is handled, or until it reaches the topmost object,
the document object.
Event bubbling is useful because it:

 Allows multiple common actions to be handled centrally.


 Reduces the amount of overall code in the Web page.
 Reduces the number of code changes required to update a
document.

The following is a simple example of event bubbling in action.

<HTML>
<BODY>
<DIV id=OuterDiv style="background-color: red"
onmouseover="alert(window.event.srcElement.id);">
This is some text
<IMG id=InnerImg>
</DIV>
</BODY>
</HTML>

Bubble event

Mouse event Generated when the user:

onmouseover Moves the mouse pointer over (that is, enters) an


element.
onmouseout Moves the mouse pointer off (that is, exits) an element.

onmousedown Presses any of the mouse buttons.

onmouseup Releases any of the mouse buttons.

onmousemove Moves the mouse pointer within an element.

onclick Clicks the left mouse button on an element.

ondblclick Double-clicks the left mouse button on an element.

Keyboard Generated when the user:


event

onkeypress Presses and releases a key (full down-and-up cycle).


However, if a key is held down,
multiple onkeypress events are fired.

onkeydown Presses a key. Only a single event is fired, even if the


key is held down.

onkeyup Releases a key.


Filters and Transactions

Filters

 Filters often create effects that can be generated with script. This
raises the question, "Why use filters if script can do the job?"
There are several reasons for using filters.
 The most important is because they don't require script. For better
or worse, many HTML authors do not use scripting. Filters are a
convenient package for the same functionality that scripting
provides.
 Another benefit of filters is that they are easier to author and can
be applied to entire classes of elements, because they use the
declarative and inherited syntax of CSS.
 Filters and transitions display properly only on systems that have
the color palette set to display 256 colors or more.
 Almost any object can have filters applied to it. However, the
object that the filter is applied to must have layout before the filter
effect will display.
 Put simply, having layout means that an object has a defined
height and width. Some objects, like form controls, have layout by
default.
 All other filterable objects gain layout by setting
the height or width property, setting the position property
to absolute, setting the writingMode property to tb-rl, or setting
the contentEditable property to true.
 You can also apply a filter to the BODY element.
The BODY element automatically has layout because it
specifically contains the client area of the window.
 However, doing so causes some filters to change when the
window is resized by the user.
 One way to avoid this is to apply the filter to a DIV that contains
all of the elements of the document.
 The following example shows how to work around applying a
filter to the BODY element.
<ELEMENT STYLE="filter:
progid:DXImageTransform.Microsoft.filtername(sProperties)" >

The following example shows a filter declaration composed of two


filters.

<IMG ID=sample SRC="sample.jpg"


STYLE="filter:progid:DXImageTransform.Microsoft.MotionBlur(stren
gth=50)
progid:DXImageTransform.Microsoft.BasicImage(rotation=2,
mirror=1); width=50%">

Internet Explorer 4.0 to 5.5 Filters Mapping

4.0 filter
Alternate 5.5 implementation
name

alpha DXImageTransform.Microsoft.Alpha

BlendTrans DXImageTransform.Microsoft.Fade

blur DXImageTransform.Microsoft.MotionBlur

chroma DXImageTransform.Microsoft.Chroma

dropShadow DXImageTransform.Microsoft.DropShadow
FlipH DXImageTransform.Microsoft.BasicImage(rotation=2,
mirror=1)

FlipV DXImageTransform.Microsoft.BasicImage(mirror=1)

glow DXImageTransform.Microsoft.Glow

Gray DXImageTransform.Microsoft.BasicImage(grayscale=1)

Invert DXImageTransform.Microsoft.BasicImage(invert=1)

light DXImageTransform.Microsoft.Light

mask DXImageTransform.Microsoft.MaskFilter

shadow DXImageTransform.Microsoft.Shadow

wave DXImageTransform.Microsoft.Wave

Xray DXImageTransform.Microsoft.BasicImage(xray=1)

RevealTrans Various. See next table.

Transactions
 Transitions are time-varying filters that affect how a change of
content is displayed. One example is changing the src attribute of
an image to display a new image on-screen.
 A transition provides an animated effect to display the new image.
You can also apply transitions to make an object fade in or fade
out by changing the visibility property.
 Transitions have methods and events to manage the timing of the
effect. When a filter completes a display update or a transition
finishes playing, the onfilterchange event is fired.
 By adding an onfilterchange event handler to capture the
completion of one transition, you can chain transitions together so
they start one after another.
 The event object supplies the necessary information about the filter
and the object involved. You can use the event object to access
the srcFilter property.
 A transition's apply method freezes the appearance of an object
when applying a transition. This allows changes to be made
without affecting the display immediately.
 The play method then invokes the transition. At any time, the
script can terminate the transition by calling thestop method. The
following example shows how to perform an automatic slide show
of images.

<HTML>
<HEAD><TITLE>Transition Fade Demo</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var fRunning = 0
function startTrans()
{
if (fRunning == 0)
{
fRunning = 1
SampleID.filters.item(0).Apply();
SampleID.src = "sunset.jpg";
SampleID.filters.item(0).Play()
}
}
</SCRIPT>
<SCRIPT for="SampleID" event="onfilterchange">
fRunning = 0
</SCRIPT>
</HEAD>
<BODY>
<IMG id="SampleID" src="beach.jpg"
style="filter:progid:DXImageTransform.Microsoft.Fade(duration=3)"
onclick="startTrans()"><BR>
Click image for Transition to Fade.
</BODY>
</HTML>

The following table maps Internet Explorer


4.0 RevealTrans transitions to the applicable Internet Explorer 5.5

syntax

revealTrans.Transition value vs. 5.5 Filters Mapping

Transition
Property Alternate 5.5 implementation
Value

0 - Box in DXImageTransform.Microsoft.Iris(irisstyle='SQUARE',
motion='in')

1 - Box out DXImageTransform.Microsoft.Iris(irisstyle='SQUARE',


motion='out')

2 - Circle DXImageTransform.Microsoft.Iris(irisstyle='CIRCLE',
in motion='in')
3 - Circle DXImageTransform.Microsoft.Iris(irisstyle='CIRCLE',
out motion='out')

4 - Wipe up DXImageTransform.Microsoft.Blinds(direction='up',
bands=1)

5 - Wipe DXImageTransform.Microsoft.Blinds(direction='down',
down bands=1)

6 - Wipe DXImageTransform.Microsoft.Blinds(direction='right',
right bands=1)

7 - Wipe DXImageTransform.Microsoft.Blinds(direction='left',
left bands=1)

8 - Vertical DXImageTransform.Microsoft.Blinds(direction='right')
blinds

9- DXImageTransform.Microsoft.Blinds(direction='down')
Horizontal
blinds

10 - DXImageTransform.Microsoft.CheckerBoard(direction='ri
Checkerbo ght')
ard across
11 - DXImageTransform.Microsoft.CheckerBoard(direction='d
Checkerbo own')
ard down

12 - DXImageTransform.Microsoft.RandomDissolve
Random
dissolve

13 - Split DXImageTransform.Microsoft.Barn(orientation='vertical',
vertical in motion='in')

14 - Split DXImageTransform.Microsoft.Barn(orientation='vertical',
vertical out motion='out')

15 - Split DXImageTransform.Microsoft.Barn(orientation='horizont
horizontal al', motion='in')
in

16 - Split DXImageTransform.Microsoft.Barn(orientation='horizont
horizontal al', motion='out')
out

17 - Strips DXImageTransform.Microsoft.Strips(motion='leftdown')
left down

18 - Strips DXImageTransform.Microsoft.Strips(motion='leftup')
left up

19 - Strips DXImageTransform.Microsoft.Strips(motion='rightdown')
right down

20 - Strips DXImageTransform.Microsoft.Strips(motion='rightup')
right up

21 - DXImageTransform.Microsoft.RandomBars(orientation='
Random horizontal')
bars
horizontal

22 - DXImageTransform.Microsoft.RandomBars(orientation='
Random vertical')
bars
vertical

23 - Apply above filters randomly.


Random
Data Bindings

 Data binding provides a way for developers to create a read/write


link between the controls on a form and the data in their
application (their data model).

 Classically, data binding was used within applications to take


advantage of data stored in databases. Windows Forms data
binding allows you to access data from databases as well as data
in other structures, such as arrays and collections.

(A)Using Tabular Data Control

 Tabular Data Control is a Microsoft ActiveX control that comes


pre-installed with all versions of IE4+. This useful control allows
you to access, display, and even sort ASCII information stored on
the server end, such as a .txt file. In other words, it creates a simple
"database" function without the need for server side scripting such
as PHP and mySQL.

 A client side language such as JavaScript handles the more


sophisticated features of Tabular Data Control. In a nutshell, TDC
renders a simple client side database.
 As mentioned, the tabular data control is available in IE 4 and
upwards. Netscape requires a plug-in for the same function to
work.

 Implementation:

The ActiveX control is initialized using the <OBJECT> tag. The


CLASSID (unique identifier) for the tabular data control is

CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83

Thus we initialize this control in a web page as follows :

<OBJECT ID="SomeID" CLASSID="CLSID:333C7BC4-460F-11D0-


1
BC04-0080C7055A83">
2
...
3
...
4
...
5
</OBJECT>
Any object, like applet, has a number of parameters. Parameters of the
object are specified using the <PARAM> tag. The tabular data control
has around 8 parameters. Here, I'll discuss only the more important
ones :

 DataURL: The path of the file that contains the data. For eg


"data.txt".
 UseHeader: Specifies whether the first line of the data file should
be used as reference names for their respective fields below. If
specified to false, use "Column1", "Column2" etc instead. The
default value is false.
 TextQualifier: Specifies the optional character that surrounds a
field.
 FieldDelim: Specifies the character that is used to separate each
field in the data file. The default character is the comma (,). For eg,
consider a data file where we have the fields data: *SomeName*|
*SomeAge*|*SomeSex*. Here, the field delimiter used is '|' and '*'
is  the text qualifier.
 RowDelim: Specifies the character used to mark the end of each
row of data. The default character is the newline (NL) character.

Thus, an example complete initialization will look as follows :

<OBJECT ID="SomeID" CLASSID="CLSID:333C7BC4-460F-11D0-


1
BC04-0080C7055A83">
2
<PARAM NAME="DataURL" VALUE="YourDataFile.txt">
3
<PARAM NAME="UseHeader" VALUE="TRUE">
4
<PARAM NAME="TextQualifier" VALUE="~">
5
<PARAM NAME="FieldDelim" VALUE="|">
6
</OBJECT>
The parameter names are not case sensitive.
The TextQualifier parameter is purely optional, though can be useful in
helping you more easily distinguish between each data entry.

First, let us consider a simple example where I store my name and age in
a text file data1.txt. Here is the file:

data1.txt:

1name|age
2~Premshree Pillai~|~19~
Now, I will extract this data and display it in a web page as follows :

Corresponding HTML page:

1<OBJECT ID="data1" CLASSID="CLSID:333C7BC4-460F-11D0-


BC04-0080C7055A83">
2
3    <PARAM NAME="DataURL" VALUE="data1.txt">
4    <PARAM NAME="UseHeader" VALUE="TRUE">
5    <PARAM NAME="TextQualifier" VALUE="~">
6    <PARAM NAME="FieldDelim" VALUE="|">
7</OBJECT>
8<SPAN DATASRC="#data1" DATAFLD="name"></SPAN>
9<SPAN DATASRC="#data1" DATAFLD="age"></SPAN>
The output will display : Premshree 19

 Note the attributes within the SPAN tags. DATASRC specifies the
data source to use, which is the same as the ID of the object we
have initialized (here, 'data1').

 The DATAFLD attribute specifies which field of the data we want


to display. The data file data1.txt had two fields 'name' and 'age' as
you can see. Specifying the DATAFLD as 'name' will display the
name.

 Now, the above example, while perfectly valid, reveals a potential


shortcoming of the technique- as we add and remove data in the
text file, we also need to then update the corresponding HTML on
the page to accommodate this change (ie: add/remove <span>
tags).

 This process quickly becomes cumbersome depending on the size


of our database and how often it changes. Fortunately for these
situations there is another way to display the data that is both
dynamic and self-correcting.
(B)Sorting Data

 For a more detailed explanation of DHTML sorting, and the


Bubble Sort algorithm, you should first visit the Bubble Sort
demonstration page and follow the related commentary.

 This page presents a JavaScript class that enables you to 'bubble


sort' tables, lists, or custom sets of HTML elements. At the bottom
of the page are links to equivalent classes for: Insertion Sort, Shell
Sort and Quick Sort.

 By using Object-Oriented Programming we remove the bulk of the


code from the page where it's executed, and create an external
JavaScript file that can be re-used on any page or website.

1. OOP Table Sorting

 The following table demonstrates the dynamic sorting of a multi-


column table using an OOP version of the Bubble Sort code which
is included via an external JavaScript file.

 How you 'trigger' the sort event is up to you. On this page we


demonstrate a number of different options which will suit different
situations and datasets. We also show how the sort can be applied
not just to tables but to lists and other structures.

id colour random

1 green 81.63

2 red 70.7

3 yellow 71.09
4 orange 11.99

5 purple 81.53

6 red 62.25

7 red

8 orange 57

9 blue 49.42

10 orange 25

11 purple 35.43

12 yellow 50.76

13 orange 35.43

14 green 5.81

15 green 80.83

16 yellow 74.47

17 red 86.3

18 purple 25.17

19 orange 49.74

20 purple 37.42
colour
Sort by            DESC?

(C)Dynamic Sorting

 This article will illustrate a method for sorting tables dynamically.


The first method will use the search property of the location object
to reload the document, which will be extended to demonstrate a
generic solution for all tables.

 The second method will show the new data binding facility
available in Microsoft Internet Explorer 4.

Consider the following table:

Number Text Date Name


100 abc 19971104 Me
400 zzz 19961003 You
300 fox 19950902 Them
50 bad 19981201 Us

 It contains a mix of different items and values. If we wanted to


display the table but sorted by a particular column, then we would
normally require a different HTML document per column.

 Using JavaScript we are able to control the output of a table,


displaying it differently depending on the column to be sorted.

Table Sorting

The following script, uses an myObjectArray object array to hold the


data to be displayed, as myObject objects, in the table.
The myObjectArray array is then sorted using
the myObjectBubbleSort() function, this is similar to the sorting
processes describe in the previous article Arrays, Object Arrays and
Sorting. Finally the myObjectArray array is output as a table using
the showObjectArray() function.

The myObjectArray array is not always sorted before being shown. It


is only sorted, if the location object has a search property that isn't
empty, i.e.sortProperty has a length greater than zero.
This sortProperty is then passed to
the myObjectBubbleSort() function which is used to dictate which
property of the myObjectArray array is to be used when sorting the
array.

When the table is ouput using the showObjectArray() function, the


headers of each column have a link which reloads the document with
the search property of the location object set to the
required myObject property.

Therefore if you click one of the column headings the document will be
redisplayed, showing the table sorted by the column selected.

<SCRIPT LANGUAGE="JavaScript"><!--
function myObject(number,text,date,name) {
this.number = number;
this.text = text;
this.date = date;
this.name = name;
}

var objectArrayIndex = 0;
var myObjectArray = new Array();

function showObjectArray(object,length) {
var output = '<CENTER><TABLE BORDER=1>';
output += '<TR>' +
'<TH><A HREF="sort.htm?number">number<\/A><\/TH>' +
'<TH><A HREF="sort.htm?text">text<\/A><\/TH>' +
'<TH><A HREF="sort.htm?date">date<\/A><\/TH>' +
'<TH><A HREF="sort.htm?name">name<\/A><\/TH>' +
'<\/TR>';
for (var i=0; i<length; i++)
output += '<TR>' +
'<TD>' + object[i].number+ '<\/TD>' +
'<TD>' + object[i].text + '<\/TD>' +
'<TD>' + object[i].date + '<\/TD>' +
'<TD>' + object[i].name + '<\/TD>' +
'<\/TR>';
output += '<\/TABLE><\/CENTER>';
document.write(output);
}

function myObjectBubbleSort(arrayName,length,property) {
for (var i=0; i<(length-1); i++)
for (var j=i+1; j<length; j++)
if (eval('arrayName[j].' + property + '<arrayName[i].' +
property)) {
var dummy = arrayName[i];
arrayName[i] = arrayName[j];
arrayName[j] = dummy;
}
}

myObjectArray[objectArrayIndex++] = new
myObject(100,'abc','19971104','Me');
myObjectArray[objectArrayIndex++] = new
myObject(400,'zzz','19961003','You');
myObjectArray[objectArrayIndex++] = new
myObject(300,'fox','19950902','Them');
myObjectArray[objectArrayIndex++] = new
myObject(50,'bad','19981201','Us');

var sortProperty = window.location.search.substring(1);

if (sortProperty.length != 0)
myObjectBubbleSort(myObjectArray,objectArrayIndex,sortProperty);

showObjectArray(myObjectArray,objectArrayIndex);
//--></SCRIPT>

(E)Filtering

Features Description

Easy Installation Tune dropdown menu parameters manually or


and Customization using Deluxe Tuner. Then add several rows of a
code within html page - your menu is ready!

Javascript API  Use special JavaScript API for:


(Javascript   - Dynamic changing of items (text, link, icons
Dynamic Menu) and even individual style!).
(Real-time   - Making a dropdown menu item
modifications) active/inactive.
  - Addition/removing of submenus (new! v2.0).
  - Addition/removing of items.
  - Changing of visibility of items.
  - Getting the information on any menu,
submenu and items.
  - Other tricks.

Cross Frame Menu Cross-frame mode allows you to build full-


featured menus on the pages that use frame-
based structure (framesets). But for all that it's
not necessary to insert any additional code into
all the pages - just specify some extra
parameters of the dropdown menu.
Keystrokes Support Opportunity to control the menu from the
keyboard.
Press Ctrl+F2 right now and use your keyboard
to control the top menu.
Press Esc to exit the menu.

new! v2.0 This technology allows to load data for


AJAX Menu submenus "on-the-fly" from the server. It saves
(AJAX-like outgoing traffic from the server especially when
Technology) using big menus.
Supported browsers:
     Windows OS: IE5+, Firefox, Mozilla,
Netscape 7+, Opera 8+
     MAC OS: Firefox

Popup Menu  Create contextual menus for your pages. The


(Right Click Menu) current coordinates of the mouse pointer or your
own ones can be used for the contextual menu.

Smart Scrollable When the submenu is larger than the visible


Feature  area of the page the submenu will be
(Javascript automatically decreased. To see all the submenu
Scrolling Menu) items you do not need to use scrollbars or
something like that - just put your mouse to the
bottom of a submenu and it will be
automatically scrolled!
You can also specify height and width for each
separate submenu.

new! v3.0 Add sound effects to all menu events, menu


Sound Support mouse over, button click.
This effect supported by IE only.

new! v3.0 Now you have a possibility to add search bar in


Search Support the menu. You can search within current
submenu only or with the whole menu.
Press Enter to move on the founded words.

CSS Javascript Build menus completely based on Cascading


Menu Style Sheets. It is possible to appoint the
(CSS-based menu) individual CSS styles for separate elements of
the dropdown menu.

Objects Submenus drop down over all the objects of the


Overlapping page (select, flash, object, embed, applet). If for
(Flash Layer some reasons a submenu can't drop down over
Overlap Menu) an object, the latter will be hidden for a time
when the submenu is shown.

Filters and These effects will make your dropdown menu


Transitional Effects more attractive and stylish. You can cast a
(Dhtml Dynamic shadow on the menu and submenus, set
Menu) transparency and transitional effects. Among
(supported by PC available transitional effects there are such as
IE5+) fade, mosaic, random dissolve, slide out and
many others.

Individual Styles Create individual styles and assign them to any


(Javascript Cascade submenu and item. Use individual styles to
Menu) achieve stunning effects!

Moving Menu Use a mouse to move a menu as a usual


(Movable window.
Menu/Drag and Also you can create the menu where each
Drop Menu) submenu can be "separated" from the menu
(MS Office toolbar-like mode).

Floating Menu When the page is scrolled the dropdown menu


remains visible. The menu can "float" along one
or two coordinate axes.

Multilevel Drop
There can be multilevel menus - create as many
Down List
rows of the menu as necessary. Any submenu in
and
its turn can include different number of
Multicolumn
columns.
Dhtml Menu Script

Ways of Showing Submenus can be shown in 4 ways:


Sub Menus     - From left to right and also from left to right
(Javascript Mouse + upwards.
Over Menu)     - From right to left and also from right to left
+ upwards (e.g. forright-to-left languages).

Image Based Use images for icons, backgrounds of submenus


Navigation and items. Using images you can create menus
entirely based on graphics.

Orientation of the
Create both horizontal and vertical menus and
Menu.
submenus with any amount of menus on one
Several Menus on
page.
One Page

Any HTML Code Insert any HTML code inside the dropdown
menu item - be it a form or a picture, a flash-
object or a text. This ability allows you to create
various menus of any complexity.

Size and You can set the size of the menu in pixels,
Positioning percent or other units.
The menu may have an absolute or relative
position (it can be inserted into the table).
Fonts, Borders and Use any necessary font of any color, size and
Background Colors font decoration.
Create any available type, thickness and color
of a menu's frame.
Choose any color for backgrounds of submenus
and items.

Padding and Specify various values for padding and spacing


Spacing for the whole menu and for each separate
submenu.

Delays and You can specify a time for delays in showing or


Prefixes hiding of a submenu.
Use special prefixes for image paths and links
to make paths absolute.

Separators Create separators using your own pictures, size


and alignment.
UNIT -5
XML Basics

Introduction

XML is a software- and hardware-independent tool for storing and


transporting data.

What is XML?

 XML stands for eXtensible Markup Language


 XML is a markup language much like HTML
 XML was designed to store and transport data
 XML was designed to be self-descriptive
 XML is a W3C Recommendation

XML Does Not DO Anything

Maybe it is a little hard to understand, but XML does not DO anything.

This note is a note to Tove from Jani, stored as XML:

<note>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>
Output:
Note

To: Tove

From: Jani

Reminder

Don't forget me this weekend!


The XML above is quite self-descriptive:

 It has sender information.


 It has receiver information
 It has a heading
 It has a message body.

But still, the XML above does not DO anything. XML is just
information wrapped in tags.

Someone must write a piece of software to send, receive, store, or


display it:

The Difference Between XML and HTML

XML and HTML were designed with different goals:

 XML was designed to carry data - with focus on what data is


 HTML was designed to display data - with focus on how data
looks
 XML tags are not predefined like HTML tags are

XML Does Not Use Predefined Tags

The XML language has no predefined tags.

The tags in the example above (like <to> and <from>) are not defined in
any XML standard. These tags are "invented" by the author of the XML
document.

HTML works with predefined tags like <p>, <h1>, <table>, etc.

With XML, the author must define both the tags and the document
structure.
XML is Extensible

 Most XML applications will work as expected even if new data is


added (or removed).

 Imagine an application designed to display the original version of


note.xml (<to> <from> <heading> <data>).

 Then imagine a newer version of note.xml with added <date> and


<hour> elements, and a removed <heading>.
The way XML is constructed, older version of the application can
still work:

<note>
  <date>2015-09-01</date>
  <hour>08:30</hour>
  <to>Tove</to>
  <from>Jani</from>
  <body>Don't forget me this weekend!</body>
</note>

Old Version
Note

To: Tove

From: Jani

Head: (none)

Don't forget me this weekend!

New Version
Note

To: Tove

From: Jani

Date: 2015-09-01 08:30


Don't forget me this weekend!

XML Simplifies Things

 It simplifies data sharing


 It simplifies data transport
 It simplifies platform changes
 It simplifies data availability

1. Many computer systems contain data in incompatible formats.


Exchanging data between incompatible systems (or upgraded
systems) is a time-consuming task for web developers. Large
amounts of data must be converted, and incompatible data is often
lost.

2. XML stores data in plain text format. This provides a software-


and hardware-independent way of storing, transporting, and
sharing data.

3. XML also makes it easier to expand or upgrade to new operating


systems, new applications, or new browsers, without losing data.

4. With XML, data can be available to all kinds of "reading


machines" like people, computers, voice machines, news feeds,
etc.
HTML vs XML

 XML and XHTML have an infinite number of possible


elements, whereas HTML has a very strict set of predefined
elements.
 An HTML document can be XML, but an XML document
can't be HTML unless it uses the named HTML elements and served
as XHTML.
 XML (and to some degree XHTML) have to be well-formed
and valid before they can be interpreted, HTML can be still be
interpreted even if it is malformed and invalid.
 XML attributes have to be quoted and can't be value-less. 
HTML attributes can omit redundant values and only need quotes in
certain conditions, unless it's XHTML, in which case it assumes
XML attribute rules.
 HTML can be parsed as text/html and application/xhtml+xml,
over and above what XML can be parsed as: application/xml.
 XML and XHTML have to have a closing element for each
open element. Depending on the element, HTML doesn't care
whether an element has a closing tag or not.
 XML elements are mostly meaningless and its parsers won't act
on those elements, whereas the elements of an HTML document
convey meaning or browser-instruction by their use.
 HTML has been in use a lot longer than XML
Syntax of the XML Document
XML Naming Rules

XML elements must follow these naming rules:

 Element names are case-sensitive


 Element names must start with a letter or underscore
 Element names cannot start with the letters xml (or XML, or Xml,
etc)
 Element names can contain letters, digits, hyphens, underscores,
and periods
 Element names cannot contain spaces

Any name can be used, no words are reserved (except xml).

Best Naming Practices

Create descriptive names, like this: <person>, <firstname>, <lastname>.

Create short and simple names, like this: <book_title> not like this:
<the_title_of_the_book>.

Avoid "-". If you name something "first-name", some software may


think you want to subtract "name" from "first".

Avoid ".". If you name something "first.name", some software may think
that "name" is a property of the object "first".

Avoid ":". Colons are reserved for namespaces (more later).

Non-English letters like éòá are perfectly legal in XML, but watch out
for problems if your software doesn't support them.
Naming Styles

There are no naming styles defined for XML elements. But here are
some commonly used:

Style Example Description

Lower case <firstname> All letters lower case

Upper case <FIRSTNAME> All letters upper case

Underscore <first_name> Underscore separates words

Pascal case <FirstName> Uppercase first letter in each wor

Camel case <firstName> Uppercase first letter in each wor

Except the first

If you choose a naming style, it is good to be consistent!


What is an XML Element?

An XML element is everything from (including) the element's start tag


to (including) the element's end tag.

<price>29.99</price>

An element can contain:

 text
 attributes
 other elements
 or a mix of the above

<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>

In the example above:

<title>, <author>, <year>, and <price> have text content because they


contain text (like 29.99).

<bookstore> and <book> have element contents, because they contain


elements.

<book> has an attribute (category="children").


Empty XML Elements

An element with no content is said to be empty.

In XML, you can indicate an empty element like this:

<element></element>

You can also use a so called self-closing tag:

<element />

The two forms produce identical results in XML software (Readers,


Parsers, Browsers).

Empty elements can have attributes.

XML documents often have a corresponding database. A common


practice is to use the naming rules of the database for the XML
elements.

Camel case is a common naming rule in JavaScripts.

XML Elements are Extensible

XML elements can be extended to carry more information.

Look at the following XML example:

<note>
  <to>Tove</to>
  <from>Jani</from>
  <body>Don't forget me this weekend!</body>
</note>

Let's imagine that we created an application that extracted the <to>,


<from>, and <body> elements from the XML document to produce this
output:

MESSAGE

To: Tove
From: Jani

Don't forget me this weekend!

Imagine that the author of the XML document added some extra
information to it:

<note>
  <date>2008-01-10</date>
  <to>Tove</to>
  <from>Jani</from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

Should the application break or crash?

No. The application should still be able to find the <to>, <from>, and
<body> elements in the XML document and produce the same output.

This is one of the beauties of XML. It can be extended without breaking


applications.
XML Attributes

XML elements can have attributes, just like HTML.

Attributes are designed to contain data related to a specific element.

XML Attributes Must be Quoted

Attribute values must always be quoted. Either single or double quotes


can be used.

For a person's gender, the <person> element can be written like this:

<person gender="female">

or like this:

<person gender='female'>

If the attribute value itself contains double quotes you can use single
quotes, like in this example:

<gangster name='George "Shotgun" Ziegler'>

or you can use character entities:

<gangster name="George &quot;Shotgun&quot; Ziegler">

XML Elements vs. Attributes

Take a look at these examples:

<person gender="female">
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>
<person>
  <gender>female</gender>
  <firstname>Anna</firstname>
  <lastname>Smith</lastname>
</person>

 In the first example gender is an attribute. In the last, gender is an


element. Both examples provide the same information.

 There are no rules about when to use attributes or when to use


elements in XML.

 The following three XML documents contain exactly the same


information:

A date attribute is used in the first example:

<note date="2008-01-10">
  <to>Tove</to>
  <from>Jani</from>
</note>

A <date> element is used in the second example:

<note>
  <date>2008-01-10</date>
  <to>Tove</to>
  <from>Jani</from>
</note>

An expanded <date> element is used in the third example::

<note>
  <date>
    <year>2008</year>
    <month>01</month>
    <day>10</day>
  </date>
  <to>Tove</to>
  <from>Jani</from>
</note>
Avoid XML Attributes?

Some things to consider when using attributes are:

 attributes cannot contain multiple values (elements can)


 attributes cannot contain tree structures (elements can)
 attributes are not easily expandable (for future changes)

Don't end up like this:

<note day="10" month="01" year="2008"
to="Tove" from="Jani" heading="Reminder"
body="Don't forget me this weekend!">
</note>

XML Attributes for Metadata

Sometimes ID references are assigned to elements. These IDs can be


used to identify XML elements in much the same way as the id attribute
in HTML. This example demonstrates this:

<messages>
  <note id="501">
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
  </note>
  <note id="502">
    <to>Jani</to>
    <from>Tove</from>
    <heading>Re: Reminder</heading>
    <body>I will not</body>
  </note>
</messages>

The id attributes above are for identifying the different notes. It is not a
part of the note itself.
What I'm trying to say here is that metadata (data about data) should be
stored as attributes, and the data itself should be stored as elements.

UNIT -6

Publishing the Site


Uploading Web pages

Using FTP and using Web Page Editors

Getting to grips with an FTP client: FireFTP


There are several FTP clients out there. Our demo covers FireFTP, since
it's quite easy to set up in Firefox. If you use Firefox, just go
to FireFTP's addons page and install FireFTP.
Of course there are lots of other options. See Publishing tools: FTP
clients for more information.
Open FireFTP in a new tab. Two ways to do so in Firefox:

1. Firefox menu   ➤  ➤ FireFTP


2. Tools ➤ Web Developer ➤ FireFTP
Now you should see something like this:
Logging in
For this example, we'll suppose that our hosting provider (the service
that will host our HTTP web server) is a fictitious company "Example
Hosting Provider" whose URLs look like
this: mypersonalwebsite.examplehostingprovider.net.
We have just opened an account and received this info from them:

Congratulations for opening an account at Example Hosting Provider.

Your account is: demozilla


Your website will be visible at demozilla.examplehostingprovider.net
To publish to this account, please connect through FTP with the
following credentials:

 FTP server: ftp://demozilla.examplehostingprovider.net
 User: demozilla
 Password: quickbrownfox
 To publish on the web, put your files into
the Public/htdocs directory.
Let's first look at http://demozilla.examplehostingprovider.net/ — as you
can see, so far there is nothing there:
Note: Depending on your hosting provider, most of the time you'll see a
page saying something like “This website is hosted by [Hosting
Service].”
To connect your FTP client to the distant server, press the "Create an
account..." button and fill in the fields with the information furnished by
the hosting provider:

Here and there: local and remote view


Let's now connect with this newly-created account:
Let's examine what you're seeing:

 On the left, you see your local files. Navigate into the directory
where you store your website (in this case, mdn).
 On the right, you see remote files. We are logged into our distant
FTP root (in this case, users/demozilla)
 You can ignore the bottom zone for now. It's a live log of every
interaction between your FTP client and the server.
Uploading to the server
As you remember, our hosting provider told us that our files have to be
stored in the Public/htdocs directory, so navigate there in your right
pane:
Now, to upload your files to the server, drag-and-drop them from the left
pane to the right pane:

Are they really online?


So far, so good, but double-check by going
to http://demozilla.examplehostingprovider.net/ in your browser:
Andvoilà ! Our website is live!
Other methods to upload files
The FTP protocol is one well-known method for publishing a website,
but not the only one. Here are a few other possibilities:

 Web interfaces. An HTML interface acting as front-end for a


remote file upload service. Provided by your hosting service.
 GitHub (advanced). Upload through git with a combination of
commit/push methods. See our Publishing your website articles from
ourGetting started with the Web guide.
 Rsync (advanced). A local-to-remote file synchronizing system.
 WebDAV. An extension of the HTTP protocol to allow more
advance file management.
How do I upload a file to my server?
 There are quite a few ways to upload a file to your server at
InMotion Hosting. How you upload your files will depend on your
preference and your accessibility to the server.
 In this tutorial, we will explain how to upload a file using the File
Manager, FileZilla, and Notepad++. We assume that you know
where within your account you need to upload your files. If you're
not sure however, please see our article entitled What directory
should I put my files in?.

What's the difference between each method


There are reasons why a developer would use File Manager, FileZilla, or
Notepad++. The following will explain why you would pick one method
or the other.
 File Manager (browser based): The File manager is good to use
when you are away form your computer and you can access a
browser. The File Manager can be accessed from any location.
This eliminates the need to install a program like FileZilla or
Notepad++.
 FileZilla (FTP): FileZilla is good to use for uploading files
because it works over port 21 and can upload mass amounts of
files all at once.
 Notepad++ (Code Editor): Using Notepad++ is a way to upload
files while you create the content for them, notepad++ is similar to
DreamWeaver in that you can Edit files and upload them through
the same interface. This eliminates the need to have an HTML
editor and a FTP program at the same time.
How to upload a file through File Manager

1.

Lo
gin into your cPanel. Click the File Managerbutton in the Files section.

2.
Navigate to the directory you want to upload a file to and click
the Upload link at the top of the File Manager. This will open an upload
page in a new tab.

3. Drag and drop your file into the window, or click Select File to
browse your computer for the file you want to upload. Check the
available box if you want to overwrite files that already exist in the
upload folder.

4. Your file will then upload. You will see a "100%" message when
the upload completes.

5. Click the Go Back link to return to the File Manager.

6. Refresh your File Manager by clicking the Reloadlink at the top


middle of the File Manager. You should then see the file listed in
the File Manager now.
How to upload With FTP using FileZilla
FileZilla has the ability to upload files from your computer to your
server with us. The Left side is the" Local Site" and the Right is the
"Remote Site". The "Local Site" is your where your computer files are
located. The "Remote Site" is the location of the files on the server.
Below is how to upload a file using FileZilla.

1. Connect to your server with FileZilla.

2. Navigate your files in the third window on the left underneath the
"Local Site:" box where its says"Filename". 

3. The Window to the right of it is the "Remote Site"


directory. Navigate to the folder where you want to upload the
file/folder to in the "Filename" Window underneath the "Remote
Site" window.

Drag the file you want to upload to the server from the "Local Site" to
the "Remote Site".
The File will upload and you will see the file in the list of files in the
directory where you dragged the file to. 
Using a program like Notepad++
Notepad++ is a program that allows you to edit your site and upload and
create files on the server. It is similar to HTML editor programs
like Edit Plus or DreamWeaver. Below will explain how to create a
file on your server with Notepad++.

1. Connect to your server with Notepad++.

2. In the NppFTP Window on the right side of Notepad+


+, navigate to the folder you want to upload a file to. Right click the
folder and select "Upload other file here. . .". 
Browse the server for the file you want to upload. Select the file and
Click open. 

Now you will see the file in the folder location on the server. 
Web hosting

Shared hosting running a Local Web server

 It's particularly useful if you don't want to spend money on


multiple Virtual Private Servers (VPS), but you'd like to have
ability to run and build multiple websites with minimum cost on
the same server.
 In real world scenario, most of those sites would be based on
common content management systems such as Wordpress, Drupal,
Joomla, etc.
 The idea lies in the fact that instead of having single root directory
for your website (which is/var/www/html/ in our example), you can
have multiple folders located in /var/www/ where each folder will
contain separate website.

What would you need to have to make it work:

 web server which already has full LAMP stack on it. As example
in this article, we use Ubuntu 14 with MySQL and Apache2 as
web server.
 root access to this web server
 root access to MySQL database on this server

What we actually would do? When you want to add new website into
your server, there are following three steps to consider:

 pointing your domain into that folder


 creating root folder for the website and setting up web server to
recognize that folder
 creating database and database user which would manage your
Wordpress or Drupal installation

Note, it doesn't matter in what sequence you are following these three
steps, as long as they all completed. And once all these steps completed,
you are good to go with installation of your CMS as per its
documentation.
 All actions shown as performed under root account. Remember, it's
best practice to use regular account with sudo rather than root to
perform any changes in your system.

Step 1: Point the domain


Point your web traffic of your  domain on to your server as per
requirements of  your domain provider. Essentially it means you would
need to create A record which resolves into your web server's IP.

Step 2: Adding virtual host into web server's configuration.


Let's assume we want to build  website called cutepuppies.com  and
related configuration files and folders in our server will be named
accordingly as cutepuppies

Make separate root directory for your new website:

mkdir /var/www/cutepuppies
 

Give ownership of the directory to the Apache web user (which is www-
data)

chown www-data:www-data -R /var/www/cutepuppies


 

Also, if you action not under root account, add your username to the web
group:

usermod -aG www-data YOUR_USER_NAME

Go to your web server configuration folder /etc/apache2/sites-available


Make a copy of default configuration file 000-default.conf and name
it cutepuppies.conf

cp 000-default.conf cutepuppies.conf
 
Open your new configuration file and change following parameters as
per below:

ServerName cutepuppies.com
Server Alias www.cutepuppies.com
DocumentRoot /var/www/cutepuppies

<Directory /var/www/cutepuppies>
DirectoryIndex index.php
AllowOverride All
Order allow,deny
Allow from all
</Directory>
 

Once your configuration file is ready, enable it with this command:

a2ensite cutepuppies.conf
 

Now to make it work after changes, you need to reload configuration of


your web server:

service apache2 reload


 
Step 3: Create MySQL database and database user
Let's assume we've defined the values for new database as following:

Database name: dbcutepups

Database user: dbuser

DB user's password: password123

 
Log into MySQL using your MySQL root credentials:

mysql -u root -p
 

Provide password when prompted. After successful login, instead of


BASH invitation you will see the one looking like this:

mysql>
 

What we have logged into MySQL for is to create database, database


user and make that user work with this database. It's simply achieved by
the following commands:

mysql> CREATE DATABASE dbcutepups;


mysql> CREATE USER dbuser@localhost;
mysql> SET PASSWORD FOR dbuser@localhost=
PASSWORD("password123");
mysql> GRANT ALL PRIVILEGES ON dbcutepups.* TO
dbuser@localhost IDENTIFIED BY 'password123';
mysql> FLUSH PRIVILEGES;
Then, you can exit from MySQL.

Now you are ready to unpack your CMS into root


directory /var/www/cutepuppies/ and to run installation. When installing
CMS, you would need to use MySQL credentials that you've just
created.

 Each time you want to add new website into your server, follow
described instructions again. If everything is working properly, all
your websites located on the server should be accesible. 
Ultimate Guide to Web Hosting

Chapter 1: What is Web Hosting?

Most people never really think about where a website is, or even what a
website is. I turn on my computer, open a browser, and go to Google or
Amazon or Yahoo. But what am I doing when I “visit” a website? If I’m
a visitor, where have I gone? And if it is a “site,” where is it located?
What will you learn in this chapter?

 What a website really is.


 Three different types of websites (and why they’re mostly the
same).
 Where a website “lives.”
 What a hosting company is.

Skip this chapter if… You have used web hosting before and have a
good understanding of what a website is and how they work.

What is a website?

To understand where a website is located, it’s helpful to understand what


it is.
We can roughly divide websites into three types (there is some overlap
here — these are not strict categories, but they are helpful for thinking
about this):

 Collection of documents or pages — This is the original type of


website. Every page is a file in a public-facing directory. When you look
at a web page, your computer is literally downloading the file and
showing it to you.
 Web application — Google, your web-based email provider,
Facebook, and any online games you might play are all examples of web
applications. Much like apps you run on your phone, tablet, or desktop,
the files for the app have to exist somewhere. With web apps, they sit on
public-facing web server the same way documents and files do. Your
browser downloads some of the files and runs them, and there is
constant communication between your computer and the web server.
 Content management systems — This is sort of a hybrid, and
accounts for the vast majority of websites that exist today. The
technology of a web application is used to simulate a collection of
documents. If you read a blog, each blog post is probably not an
individual file. Rather, the application is pulling the content out of a
database and sending it to your browser as if it were a document, and
your browser shows it to you without knowing any different.
There’s some additional complications we don’t really need to get into
here, but the important thing is that when you visit a website, a series of
things are happening:
1. Your computer’s browser sends a request to the website’s server
for something — a page, a document, a file for running an application.
The URL or address you put into the bar at the top of the browser
window is the main portion of that request.
2. The web server receives the request and pulls together whatever it
needs to deliver back to you what you requested. This might just be an
existing file, or it might be a piece of a web application, or it might be an
assembled document from a content management system.
3. The web server responds to the request with some kind of content.
4. Your browser shows that content to you.

Running a website

So, in order to run a website, you need a computer connected to the


internet, that is capable of receiving requests, taking appropriate action,
and responding. When people talk about servers for their website, this is
all they are talking about. Computers that store the files needed to run a
website, along with the software to deliver those files to anyone who
asks for them.
You could, in theory, run a website from your home desktop computer,
but that would be a terrible idea.
First off, you’d have to know how to set it up properly to run a website
(which is not a trivial matter). You’d have to leave it on and connected
to the internet all the time. Even if you could manage those things, your
computer at home is only designed to deal with one user at a time. If a
lot of people started trying to look at your website, your computer and
your internet connection would both reach their limits and your website
would stop working.
Better than running a website on a personal desktop computer, you could
buy a server. This is just a bigger, faster, better computer. Assuming you
could afford it (they’re expensive) and assuming you could set it all up
properly (it’s not easy) and assuming you could get a fast enough
internet connection with a lot of bandwidth (expensive and not always
available), you could then run your website from that server.
Obviously, this is a terrible idea. Too expensive, too complicated, too
difficult.

Web hosting companies

Web hosting companies have solved this problem for you. They have
bought the big expensive computers, they have set them up to work for
running a website, they have made sure they have a fast connection to
the internet. They’ve done all the work.
When you get a web hosting plan, you are borrowing a bit of one of their
computers (or a whole one, sometimes). This lets you put the files and
software needed to run your website somewhere that it can easily be
accessed by anyone who wants to view it. To make this easier for you,
they also provide tools for managing your piece of the computer and for
building and running your website.
When you use a web hosting company for your website, your website
isn’t in a cloud somewhere or floating in an alternate dimension. It is a
collection of real, actual computer files sitting on a real actual computer
somewhere, in a real building. Where that building is, and what that
computer looks like will depend on which hosting company you use.
And you may never see the computer or even know where in the world it
is. But it’s not magic, and it’s not that much different than the computer
you are using right now.
Summary
A website is a collection of files that sit on a computer. For a website to
work well, a regular desktop computer isn’t a good choice. Web hosting
companies provide fast, powerful computers so that anyone can run a
website without having any special knowledge or buying any special
equipment.
Chapter 2: Different Types of Hosting

When you start looking to purchase a web hosting plan, it’s easy to start
getting overwhelmed by all the different options available. Rather than
trying to sort out what to buy while reading feature lists written by
marketers, it’s better to start by figuring what kind of hosting you need.
What will you learn in this chapter?
 The difference between shared, dedicated, and VPS hosting.
 What “cloud based” hosting is.
 What managed hosting is, and why you may or may not need it.
 How to decide what type of hosting plan is right for you.

Shared Hosting

The most common form of web hosting is called "shared hosting." It is


the least expensive and, as you might guess, the least powerful.
With shared hosting, several web hosting customers share the same
computer. All of the websites of all the different accounts are stored in
the same drive, processed by the same CPU, and delivered by the
same web server.
It’s easy to see why this is less expensive than other options. The hosting
company is allocating relatively few resources to you.
Of course, there are downsides. All the websites from all of the accounts
are all competing for the same scarce computer resources.
The servers that hold shared hosting plan sites are much larger and more
powerful than your home computer, so they can host hundred of
websites without any problem — as long as none of the sites are too
popular or need too many resources.
Every page load, every image and asset file, requires a little bit of
attention from the web server when someone requests it. If you are
running a complex web application or a content management system,
this could require more than a trivial amount processor power to query a
database, assemble content into a page, or take some other action.
Individually, these things can be so fast as to seem instantaneous. But
multiplied over hundreds or thousands of visitors in a few minutes, and
you have a recipe for site crashing.
If the popular site is someone else’s on the same server, you’ll
experience performance lags and downtime without ever knowing why.
If you are the lucky one getting a lot of traffic, you can expect your site
to become unavailable right when you most need to shine. Additionally,
you may find yourself running afoul of your hosting company’s unstated
but very much in-force limitations on usage and bandwidth.
The other downside to shared hosting is the inability to customize the
hosting environment. This might not make any difference to you. If you
are just running a straightforward WordPress blog(for example), you can
get by just fine without having to tweak your environment. But if you
are trying to run something more complicated, like a custom application
built on a complex framework, you’re going to run into trouble when
you can’t get all of your dependencies installed correctly.
One last problem to note about shared hosting is that it opens your
website up to a certain amount of risk. No matter how careful you are in
securing your web applications, other people might leave their software
vulnerable to attack and provide an entry point for attacks that affect
your site as well. Additionally, you share the same IP address with other
sites on the same server. If one of them is using their account to send
spam emails, or is engaging in other bad behavior, you may find your
sites being blocked by email filters and content firewalls. The worst part
about this problem is that you might not even know it’s happening.
Dedicated Server Hosting

With dedicated server hosting, you have complete control over an entire


server. This has many advantages, but it is also more expensive and
more complicated.
When you have direct and complete access to the server that is running
your website, you can install any kind of niche software you like, make
changes to the operating system or language interpreters, tweak
configuration settings. For certain applications, like running an
enterprise management system or building custom software, you need
this level of control.

The other major advantage to a dedicated server is that you are the only
one consuming server resources. This significantly increases your speed
and performance.
Of course, if you are able to do anything you want on your server, you
also become responsible for doing pretty much everything that needs to
be done. This includes keeping all the software up to date and debugging
issues if you accidentally create any weird conflicts or problems.
Dedicated server hosting can be very expensive also. With shared
hosting, there might be 100 customers on a single server. With a
dedicated server, you are the only one — and the difference in cost
reflects that.

Virtual Private Server

Somewhere between shared hosting (a lot of people on one server) and


dedicated hosting (one account on a server), is Virtual Private Server
(VPS) hosting. In this model you have your own dedicated server, but
the server is a virtual machine, not a physical one.
This provides a mix of the benefits (and disadvantages) of both shared
and dedicated hosting plans.
With VPS hosting, you have complete control over the environment, just
as you would with a dedicated server. This is especially helpful if you
are developing custom applications or are running a SaaS (software-as-
as-service) business.
You generally have much more access to server resources with VPS
hosting as compared to shared hosting. While the various virtual
machines are all sharing server resources, there are usually many fewer
of them on a server in a VPS environment. You are alloted a much larger
portion of the overall computing power and bandwidth.
There also many fewer security issues. VPS accounts have their IP
address, and the virtualization layer means that you are insulated from
any problems that might arise from problems on other sites.

Scalable Cloud-based VPS Hosting

The problem with both dedicated servers and conventional VPS and
shared hosting plans is that eventually — if there’s enough traffic — you
will hit the physical limitations of the actual server. We’re talking about
a real machine with real limitations on how much memory it can use,
how much storage it can hold, and how many requests it can handle.
Most websites never hit these limits, and shared or VPS hosting is more
than adequate. But some sites regularly get tens of thousands of visits a
day, and other sites with less regular traffic occaisionally have huge
spikes that can’t be predicted, like when a piece of content suddenly
goes viral.
Because of these hosting realities, hosting companies offer something
that usually goes by a name like “scalable VPS hosting” or “cloud based
hosting” or “scalable cloud-based hosting.”
“The Cloud” is sort of a marketing fiction, and sort of a metaphor. It’s
easy to get confused about what this means. The truth is, it means
different things in different contexts.
Generally, with regards to web hosting, “cloud” means that a large
number of computers are all clustered together, and any applications
running on them can make use of their combined computing resources.
With this type of hosting, your Virtual Private Server isn’t one of several
on a single server. Rather, it is one of hundreds all sharing a giant pool
of computing resources.
Typically, hosting companies try to keep the average level of resource
use well within the limits of the actual amount of computing power on-
hand. This might be as low as 50%. If there is a sudden increase is use
because one site has a spike in traffic, overall usage spikes but stays
within what the system as a whole can handle.
This works well for sites as they grow over time, also. The hosting
company adds more computing resources, or reorganizes how the virtual
machines are deployed on the system, in order to maintain optimum
performance as each site’s usage profile evolves.
Another benefit to scalable cloud hosting is that you usually only pay for
what you actually use. This is especially good for businesses that don’t
have the money to pay for high-end web hosting in the beginning, but
will eventually need the bandwidth if the business becomes successful.
One of the other neat features of some cloud-based VPS plans is that you
can actually have multiple virtual servers tied into one single account.
This is good for people who need a multi-stage development and
deployment structure, with a server each for dev, test, and production.
The thing to watch for with cloud-based or scalable hosting is that
“cloud” barely has any legal or technical meaning, and “scalable” is
equally ambiguous. Each hosting company has wildly different plans
under this umbrella of related terms, so be sure to read the actual
features you are purchasing, as well as reviews from real users.
Managed Hosting

If you need the bandwidth and power of a VPS or Dedicated Server, but
don’t have the technical skills (or the inclination) to do serious server
administration, you can get a managed hosting plan.
Managed hosting is a term that covers a lot of different types of plans,
but what they all have in common is that the hosting company provides
some sort of proactive technical support. This might be as simple as pre-
installing software and helping with initial configuration, to ongoing
monitoring and upgrading.
With some managed hosting plans, you have direct access to a VPS or a
dedicated server, and the hosting company provides support in addition
to that core hosting service. This gives you the flexibility to do what you
want or need to do, but without needing to know everything about server
administration.
Other managed hosting plans are geared toward specific applications
like WordPress, and your interaction with them is limited to the one
installation. The entire environment has been configured to provide the
best experience with one application, and there isn’t really anything else
for you to do. This is great if that’s the application you need, but it
doesn’t give you much flexibility.
Specialty Hosting

The hosting plans covered above account for the majority of offerings
from commercial hosting providers. The range of features, bandwidth,
and computing power available in one of these “conventional” hosting
plans will suit the needs of almost all people looking for web hosting
plans.
Just for the sake of completeness, it is worth noting that there are a
number of specialty hosting providers which specific hosting features
and support for various technology needs. Most of these are platform
specific, such as hosting geared to a particular language, database tool,
or framework. Others provide customized tool for certain development
methodologies.
The best advice is to not worry about these things at this point. If you are
setting up a website or blog for yourself, your business, or your
organization, it is highly unlikely that you will need some kind of
specialty hosting environment.
If you aren’t sure about your particular situation, you can use
our Compare Features Tool to see which hosts support the technology
you need.
How to know what kind of hosting you need
Shared hosting is a good fit for personal blogs, websites for small to
medium sized organizations like clubs and churches, and small non-tech
business. It it probably not appropriate for a business that relies
exclusively on its website for revenue, or for a large organization with a
lot of traffic. Also, any type of serious custom develop is usually not a
good fit with shared hosting.
VPS hosting is the right choice for most medium to large organization,
online stores, or major blogs. Depending on the relative size of future
traffic, you may need a “scalable” VPS solution that will be able to
handle large amounts of traffic. If you’re trying to start an online
business or launch a website for a well known brand, VPS hosting
should probably be where you start looking.
A dedicated server plan provides few real benefits over a VPS plan, and
can sometimes be more difficult to manage. This is really only a
reasonable choice if you have a server administration talent in your
organization and a compelling reason to run your applications without a
virtualization layer.
Summary
There is a lot of variety in available web hosting plans, but they all fall
into one of three categories:

 Shared hosting
 VPS hosting
 Dedicated server hosting

Shared hosting is very cheap, but not very powerful. It is good for small
projects on a budget.
Dedicated hosting is very expensive and complicated. If you don’t know
whether you need it, you probably don’t need it.
VPS hosting, which is often “cloud based” or “scalable,” is the right
default choice for most serious business customers.
Both VPS and dedicated server plans are available in “managed hosting”
plans, which may be the right fit for you if you need the power and
flexibility of a complete server but don’t have the skills or resources in
your organization to manage the server yourself.
Once you have decided which type of hosting is right for you, you can
use our Hosting Features Comparison tool to compare your various
options.
Chapter 3: What are you buying when you buy web hosting?

Web hosting is an intangible service. You can’t really see it or touch it.
Because of that, its easy to think that all web hosting plans are the same,
or that web hosting isn’t worth paying for.
Extremely cheap hosting companies rely on this intangibleness to
suggest you only need to pay a few dollars a month, and that more
expensive plans are not worthwhile. At the same time, highly overpriced
hosting companies rely on it to sell otherwise normal hosting plans at
exorbitant rates, using marketing to make similar services seem vastly
different.
In order to make the most of your web hosting, and understand the
various pricing schemes available, it’s helpful to know what you are
actually buying when you buy web hosting, and what the company is
spending your fees on.
Servers

Though you will never see it, one of the biggest expenses of web hosting
is the physical equipment, the servers themselves. These are very fast
and powerful rack-mounted computers.
Of the many things that premium web hosting companies can do to
improve their service, using better (and more expensive) equipment is
one of the most impactful. Faster equipment mean faster website load
times, which is good for you and for your website visitors.

Data Centers
Servers have to sit somewhere, so an included expense is the physical
building where a server is located. These are usually very large buildings
housing hundreds or thousands of servers.
These buildings, and the equipment in them, have to be cooled,
maintained, and guarded. Datacenters use a lot of electricity, and they
have to be located somewhere that very high speed, high bandwidth
internet access is available.

Software

While much of the software used in web hosting is Open Source (like all
four elements of the LAMP stack), not all of it is. Notably, the most
popular control panel available for web hosting accounting management
(CPanel) is proprietary software that must be licensed and paid for.
If you need a Windows hosting plan, most of the software on the server
is proprietary, which is why Windows hosting is usually much more
expensive than Linux hosting. This is why you should only use
Windows hosting if you have a very specific need for that platform.
(Most people do not.)
Internet Connection

Web hosting companies are not internet service providers — they have
to purchase internet connectivity just like you do, and run their
connections over someone else’s cables.
Actually, it’s worse (more expensive) than your own internet service
because web hosting data centers need speed and bandwidth at orders of
magnitude higher than you have in your home or business. They are
running hundreds or thousands (or hundreds of thousands) of servers,
each one requiring internet connectivity at least as fast as your home or
workplace service.

Support

If you want to call someone, or get a prompt answer when you email,
you’re going to have to use a hosting company that provides at least
some level of support.
Support might come in the form of FAQs, knowledge base articles,
detailed guides, phone support, email support, or a help desk ticketing
system. Proactive server management can be thought of as a form of
support.
As with all things, you can expect that a more comprehensive support
program is going to cost more than an otherwise equal hosting package
without a support plan.

Business Overhead

Naturally, web hosting businesses have all the usual expenses of a


business — from office space to taxes. This is not terribly relevant to
you as a customer, but it does explain why some hosting companies are
able to provide more service for less cost. You shouldn’t assume that
less expensive always means less value. Some companies are just better
managed.
Ignore pricing first

It is easy to look around at available hosting plans and pick the cheapest
one, assuming they’re all about the same. The other common option is to
pick the most expensive one because it must be the best.
Neither of these is a good way to shop for a web hosting plan.
A better way is to think through what you need from your web hosting
company and what type of web hosting is required, and then compare
several plans that fit your minimal requirements. You should also read
reviews.
Once you’ve narrowed it down to the hosts that fit your needs, and
eliminated companies with a lot of bad reviews or outrageous pricing,
you’ll usually be left with a small handful of hosting plans at very
similar price points.
Summary
Price is not always a good indicator of quality. There are plenty of very
decent, low priced web hosting companies. However, if you need
something more than “very decent” you are going to have to pay more
for it. Premium web hosting — with fast processors, better connectivity,
lower downtime, and a higher level of support — costs more to provide,
and so it naturally costs more to purchase.
Rather than shopping based on price, it is better to begin by looking for
which features you need and finding hosting companies that provide
them.
Chapter 4: Features to Look For in Web Hosting

What will you learn in this chapter?

 How to compare speed, bandwidth, and storage features.


 Why the ability to upgrade later is more important than figuring
out exactly what you need now.
 The one thing the author of this guide always looks for before
buying a hosting plan.

Speed

It’s important that your website load as fast as possible. If visitors to


your site have to wait a long time for your page to load, they will not
have a good experience, and may not come back. Additionally, Google
now includes speed as part of their overall score of the quality of a site,
so slow loading can kill your other SEO efforts.
Unfortunately, a lot of different factors affect the speed of a website, and
only some of them depend on the web host. And pretty much every web
host advertises that their service is “blazingly fast.”
Most shared hosting plans, and many VPS ones, don’t specify to the end
user the exact details of their hardware setup. Even when they do,
sorting out the details of whether one company’s hardware is faster than
another company’s hardware is pretty much an exercise in guessing.
Also, with shared hosting especially, it isn’t the hardware alone that
determines how quickly requests are processed, but also the overall
usage of the system. A fast system running 1000 other websites may be
slower than a middle-of-the-road system that only handles one.
However, there are clues you can look for to determine if one host will
be faster than another.
Specific things to look for that tend to increase speed in web hosting:

- Detailed server hardware stats. As mentioned above, the details are


sometimes tough to sort out, but the fact the hosting company is
advertising their server setup is usually a good sign. This means (at
least) that they aren't running their service on top of someone else's
equipment.
- SSD, or Solid State Drives. These are much faster than traditional
spinning disk drives.
- Location. The closer a data center is to your visitors, the faster the page
loading will be. If it is likely that your visitors will all be one area,
choose a host with a data center near there.
- CDN, or Content Delivery Network. Many hosting companies offer
built-in partnership with a Content Delivery Network. This will
dramatically increase the speed of the site, as it offloads images and
other resources to faster servers.
An important consideration with all this is not just absolute speed, but
consistency. If a site is usually exceptionally fast, but then is really slow
sometimes, that is worse than if it was only decently fast all the time.
A good way to gauge speed and consistency is to read reviews of hosting
companies in our review section. People who have had experiences of
their own site slowing down tend to make this known in their own
reviews.
It should be kept in mind that what you do with a server will have a big
impact in how fast your site runs. Remember to optimize your site code,
limit use of plugins, use any relevant caching tools, and implement a
CDN.

Bandwidth

Bandwidth is a measure of the amount of data flowing from your


website to visitors in some specific time period, usually per month.
Many shared hosting accounts offer “Unlimited” bandwidth, but this is
predicated on the assumption that you won’t actually use very much (or
that, on average, account customers won’t use very much).
If you are running a personal blog or a site for a small business, and you
don’t expect traffic to exceed a few hundred visitors each day, then
shared hosting’s “Unlimited” bandwidth is going to work fine for you.
If you’re building a larger site that is going to eventually need to handle
thousands or hundreds of thousands of visitors every day, then paying
for bandwidth is going to become an issue.
If you are moving from one host to another, you can analyze your
current traffic (and trending) to determine how much bandwidth you
need in a plan.
Otherwise, if you are starting a new project, and don’t have much sense
of what you’ll end up needing, or how fast you’ll get there, you are
better off getting a plan where your hosting costs are variable depending
on traffic.
Be careful to steer clear of hosting plans that have penalties for going
over your alloted bandwidth amount. This can become very costly, and
is a good reason to look for plans where you pay for what you use.
Finally, it’s worth nothing that the things you can personally do to
increase speed (using a CDN, minifying your assets) will decrease your
bandwidth usage.

Storage

How much storage do you need? As always, this depends.


As with bandwidth, most shared hosting plans claim to offer “unlimited”
storage capacity, but that always comes with restrictions. However, if
you are running the type of website that shared hosting plans are
designed for (personal blogs and small business sites) you will be fine.
Unless you are specifically building a website that needs to host a lot of
high resolution images or music files, it is unlikely that you will need
more than 1GB of space — site files and text content simply don’t take
up that much room.
If you are building a normal site that happens to have a lot of images —
for example, a blog with several images per post, or an ecommerce site
with a lot of product photos — you’ll probably be fine with 2 to 4 GB
for a good long while.
You really shouldn’t try to use your web hosting account for large media
hosting. It’s an inefficient use of money. If your site needs massive
amounts of large media files, use other services (like YouTube for
videos).

Scalability

The problem with starting a new website is that you don’t really know
what your specific needs are going to be in the future. You can make
some guesses about how much bandwidth and storage you’ll need, but
those are usually only guesses.
For this reason, one of the more important things to look at when getting
web hosting is: how easy is it to upgrade.
If you start with a shared hosting plan, expecting to move up to VPS
when traffic reaches a certain point, will your web host be able to do
that? Without creating a break in service?
With VPS hosting, do you pay by the penny as usage goes up, or is there
a hard limit followed by massive overage charges? Will your host be
able to keep up if your site makes it to the first page of reddit or
slashdot?
It’s important that your web hosting account is able to handle both slow
and steady growth (through a reasonable upgrade path) and also sudden
spikes in traffic.
Even if you only plan to use a small, shared hosting account, look at the
larger VPS plans from the same host. If the shared plan costs $3/mo, but
the upgrade to VPS takes you to something really unmanageable, you
might be better off paying an extra couple of dollars per month in order
to have a more appropriate upgrade option later on. Also, it isn’t a good
idea to choose a web hosting company that only has shared hosting
plans.

Technology

Most of the issues concerning specific technology were covered in the


chapter on “How a Server Works,” but there’s a few points worth
mentioning here.
If you are planning to run most any common PHP application, like
WordPress, Drupal, Joomla, Magento, Zen Cart, MediaWiki, similar
software, you shouldn’t have any problem with the vast majority of web
hosts. They all run a LAMP stack efficiently.
Where you might run into problems is if you need something a little
more exotic. Examples include apps built on Ruby on Rails or
using MongoDB. These two things are increasingly popular, but not all
web hosts are well suited to them.
The good thing about web hosting and out-of-the-ordinary technology is
that if you don’t know whether you need it, you’re probably fine. The
vast majority of blogs and business websites will work just fine on
WordPress or a similar Content Management System, and that will work
on almost any web hosting account. You shouldn’t be using the weird
stuff unless you have a compelling reason to do so.

Access

Almost all web hosting companies provide a control panel for managing
your hosting account. But not all of them make it easy to access your
account in other ways.
At the bare minimum, you want to be able to have FTP access to your
files. SSH (secure shell) access, which gives you a command line
interface to the server, is a good thing to have also, even if you don’t
plan to use it (you never know).
You should also find out if you can install additional programs on your
server, and how difficult that is. This might not be an issue for you
(maybe you’ll never use anything except WordPress forever), but it is
good to know ahead of time, especially if you even think you might
want to run other apps.
Support
Unless you are truly just running a personal blog and don’t care if it goes
down, make sure you find a hosting company with a good customer
support plan.
There are always problems. Even with the best web hosting company
and the most straightforward website, there will always be issues of one
sort or another. Technology is just too complicated for that not to be the
case. You want to make sure you have a hosting company that will help
you deal with the problems when they come up.
I wouldn’t sign up for hosting unless the company had a 24/7 phone line
I could call. Your personal requirements might be less strict, but think
about what they might be. If you have an unexpected outage at 3am, do
you want to have to wait until business hours in Salt Lake City before
you can talk to someone?
Concerning customer support, you should definitely read reviews in
our customer review section. People have had wonderful experiences
with the support staff of various hosting companies… and also not so
wonderful experiences. Reading reviews will help you understand what
kind of experience you might have.
Chapter 5: How a Web Hosting Server Works

It’s helpful to know just what is happening with a server running a


website. Web hosting companies do a good job of marketing their
features and benefits, but they don’t usually explain the basics.
What will you learn in this chapter?
 What an operating system, web server, database, and application
language are.
 Which option for each of these is most popular in a web hosting
environment.
 The difference between a server and a web server.
 What the LAMP stack is.

A hosting server is just a computer

When it comes down to it, we’re talking about something not that
different than your personal desktop or laptop computer. Servers are a
little bigger, a lot more powerful, and don’t usually have their own
monitors and keyboards, but at heart they are just like the computers you
use everyday.
Besides being a lot more powerful, the computers used to run websites
have very fast connections to the internet, so that a lot of visitors can
access the server at the same time.

Server Operating Systems

The operating system is the primary interface between applications,


users, and the physical computer. You use an operating system
everyday, even if you’ve never thought about it.
If you have a PC, your operating system is Windows. If you are on a
Mac, you have OSX. Your phone probably runs on either Android or
iOS.
Just like you home or office computer, servers need an operating system.
The most common operating system for servers is Linux.
If you’re unfamiliar with Linux, or have heard about its difficulties for
personal computing, don’t worry. While very few people use Linux for
their home or office desktop machines, Linux is the absolute standard
for servers. It’s easy to use, also. Web hosting companies
provide control panels, management utilities, and installation tools so
that you don’t need to know (or care) about Linux at all to have a
successful experience with web hosting.
Some hosting plans provide servers running the Windows Server
operating system. Do not get confused here. Even if you are running
Windows on your own computer, that is no reason to use Windows on
the server as well. There’s no real benefit to matching those operating
systems.
The only reason to use Windows for your server is if you need it to run
some proprietary software that simply won’t run on Linux, like .NET,
ASP, or Microsoft Silverlight.
For anything else — WordPress, Drupal, Joomla, any app written in
PHP, anything built with Ruby or Python — Linux is the preferred
operating system.

Web server

“Server” refers to the physical or virtual machine, the computer that


holds your website’s files and database.
Unfortunately, there can be some confusion of terms because there’s
also a piece of software called a “web server.” The web server is the
software program that is responsible for handling requests from the
internet.
When you type a URL into the address bar of your browser, that gets
translated into a request that is routed to the computer that hosts the
website you are looking for. The web server — that is, the software
program called the web server — handles the request. It reads the
request, figures out what other applications need to get run or files
accessed, and then once that is completed, it sends a response back to the
browser. The response it sends back is (usually) the page of the website
you are trying to look at. The webserver software acts as a mediator
between the internet and the files on the server.
The most common web server is an Open Source program called
Apache. You will find it in most web hosting plans. There are a few
alternatives, the most common of which is probably nginx. If you
happen to be running a Windows server, you might be running IIS.
Unless you have some incredibly specific needs, Apache is perfectly
fine. For the most part, you will never notice or care much about your
web server.

Database Management System

Most (not all, but most) websites require a database management


system in order to store content and other information. That could be
blog posts, pages, product information, data on customers, or any other
kind of content, depending on the kind of website you are running.
The most common database management system is MySQL. This is a
very powerful, Open Source software tool for running complex
relational databases. It is free to use, and is already available on many
web hosting plans.
MySQL is the database of choice for the most popular content
management systems, such as WordPress, Drupal, and Joomla. It also
powers a number of ecommerce platforms, website builders, bulletin
board systems, and social networking applications.
There are a few other database systems that are used by particular
applications, and you might run across these if you are doing something
unique.
For example, PostgreSQL is an Open Source RDBMS that is
functionally very similar to MySQL, and it is the default database for
Ruby on Rails. So if you are using that framework, you should make
sure that you find a hosting company that supports it.

Application Layer — Scripting Languages

Most (not all, but most) websites today are dynamic in some way.
Thinking back to the database and the web server in the last two
sections, it’s clear that there needs to be some software that fetches
content from the database and sends it to the web server. This is what
applications likeContent Management Systems (CMS) are all about.
Whether its a simple blogging engine, a complex CMS, an ecommerce
site, or project management system (or anything else), websites with
interactive features and dynamic content are computer programs, and
they have to be written in a programming language. You don’t have to
know the language to use the program, but your web hosting server
needs to know it.
The most popular language for dynamic web applications is PHP, and
you will find that the vast majority of web hosts support this language. If
you need to use an application (or develop an application) in another
language (Ruby and Python are both popular) make sure that you find a
web hosting company that supports the language you need.
LAMP Stack

In each section above, I identified the most commonly used option in


each category: Linux for the operating system, Apache for the web
server, MySQL for the database, and PHP for the application.
These four technologies are sometimes referred to as the "LAMP stack",
with LAMP being an acronym (Linux, Apache, MySQL, PHP). If you
see web hosting or application requirements mention a LAMP stack, that
what this means.

Modules

Certain applications require specific modules or plugins to one or more


of those technologies. The two most common places that require
additional modules are the Web server (Apache) and the Application
language (PHP).
For example, if your application is going to have pretty URLs (clean
URLs with human-readable names instead of computer generated
codes), your application might require the Apache mod_rewrite module.
If your application does a lot of server-side work with images, you might
need the GD Graphics Library for PHP.
It is a good idea to look into the specific requirements of your intended
application, and then compare different web hosting companies to see if
they have the features you need.
A note about versions

All of these tools have different released versions, for example PHP


4.4 and PHP 5.2. Most web hosting companies use the latest stable
release for any technology, but policies vary.
You usually do not have to worry about things like modules and version
numbers if you are using a one-click installation tool
like Softaculous, Fantastico or Simple Scripts. However, if you are
installing something manually, it is worth double checking this sort of
thing.
Summary
A server is a computer (physical or virtual) that runs a website. Sitting
on that computer is a suite of interrelated pieces of software that run
your site.
The following two are absolutely required:

 The Operating System


 The Web Server

If you are doing anything other than serving static files, you also need:

 Database
 Programming language
The most common choices for these four items are the LAMP
stack: Linux (operating system),Apache (web
server), MySQL (database), PHP (programming language).
Be sure that the web hosting provider you choose supports the
technologies required by the applications you plan to use.
Chapter 6: WordPress and Hosting

If you are setting up a new website for the first time, WordPress is a


really good option. It is easy to use for beginners, widely supported on
inexpensive hosting plans, and provides a great platform for learning
about websites and development while also launching something useful.
As important as how easy it is to use is how flexible and powerful
WordPress is. Unlike “no coding required” website builders with cute
drag-and-drop interfaces, WordPress is real, professional-grade
software. As your business and website needs expand, and your skills
improve, WordPress will not become a hindrance. It is a platform you
can grow into, instead of grow out of.
Since WordPress is so popular, and since we recommend it for
beginners, it would be a good idea to explore some of the issues
surrounding web hosting with WordPress.

Shared Hosting for WordPress

Most shared hosting companies are optimized for installing and running
WordPress, and large percentage of WordPress-powered websites are
hosted with shared hosting plans.
From a basic technical standpoint concerning requirements and set up,
shared hosting is perfectly fine. In fact, WordPress itself recommends a
shared hosting provider (Bluehost) as their number one recommended
hosting provider.
There’s a problem with this though — shared hosting plans are usually
not a good fit for high-traffic sites. This is especially the case with a
dynamic CMS like WordPress. Every page view requires a database
query and interpretation of one or more PHP scripts. When the traffic
spikes, this can quickly overload your shared hosting account’s capacity,
especially if you are running a lot of plugins or a poorly designed theme.
For this reason, we recommend shared hosting as a good option only for
personal blogs and small websites.

VPS Hosting for Wordpress

For a large or complicated WordPress site that is expected to get a lot of


traffic, a scalable VPS hosting solution is usually going to be a better
choice than a shared hosting provider. Having more space and more
control over the hosting environment can help a lot, but the increase in
speed and bandwidth is the big issue here. With the right VPS plan, you
don’t have to worry about hitting the (sometimes unstated) limits placed
on shared plans.

Managed WordPress Hosting

If you are running a serious business website with a lot of traffic, you
night be a good candidate for a managed hosting plan. These plans bring
a level of service beyond simply having better access to technology
(though they often come with that as well).
Managed WordPress hosting can cover a number of value-added support
services, such as making sure your website software stays up to date and
secure. Automated backups, downtime monitoring, advanced analytics,
and proactive security measures are all features commonly found in
managed WordPress hosting. Some managed hosting plans even include
their own distributions of WordPress with special plugins and packages
designed to increase performance, security, or user experience.
WordPress is built with a strong DIY (do it yourself) mentality, and is
relatively easy to use for beginners, compared to other options available.
Managed WordPress hosting isn’t a requirement by any means, and the
advantages it provides can usually be achieved by interested individuals.
What managed WordPress hosting really offers you is time. You could
easily learn to take care of things yourself, and do the work yourself. But
it may make better business sense to simply pay a little more to a hosting
company and let them take care of things for you.

How to have the best possible WordPress hosting experience

Whether you are on a discount shared hosting plan, or the most


expensive managed VPS you can find, there are a number of strategies
that will improve your WordPress performance and hosting experience.

Keep your core WordPress install and plugins upgraded to their latest
versions.

The vast majority of security problems with WordPress have to do with


people running out of date versions of either the core software or
plugins.
Besides general neglect, the biggest reason people don’t update their
core and plugins is fear that there will be a compatibility issue.
This sort of thing does not happen often, and is less prone to happen if
you keep things upgraded all the time. If you miss an update, and are
suddenly having to jump several versions, this can cause problems.
Only use plugins that have a large user base and seem like they are
actively under development.

A big contributor to version compatibility problems is plugins that are


no longer under development. If a project is no longer releasing new
versions, it is only a matter of time before a new update of WordPress
core introduces some incompatibility problem. This is even more likely
if the plugin code is poorly written, which is often the case with
underused and underdeveloped plugins.
A large user base helps to ensure that the plugin will continue to be
developed. Even if the original developer decides to leave the project, a
large user base makes it more likely that someone else will take over and
continue making updates and adding new features.
Also, almost all plugins have bugs at some point. If a project is still
under active development, you have a way to the report the bug and it
might get fixed in a future release. Even if it doesn’t get fixed, a large
user base makes it more likely you’ll be able to find someone who has
fixed it or found a workaround or some other viable solution.

Backup your code and database regularly.

This should be old news by now, but way too many people do not
properly back up their WordPress content or theme files. Things go
wrong, sometimes — it’s best to have things backed up.
Also, if you are properly and securely backed-up, you can stop worrying
about updates potentially messing up your site. If something does go
wrong, you can just roll things back.
(WordPress itself reminds you to back up your site before updating
things, but so many people just skip right past those warnings.)

Do not host your own videos.

Just because WordPress allows you to upload and embed videos doesn’t
mean you should.
Videos use up a lot of storage space and a lot of bandwidth, so you will
quickly max out the capabilities of your hosting plan if you start
uploading videos on a regular basis.
Beyond that, do you really want to convert your video to different sizes
and resolutions so that it works equally well on different screen sizes
and with different connection speeds? Now you’re talking about extra
work (to produce different versions) and storing all those different
versions in your hosting account.
If you want your videos to be available publicly, host them on YouTube,
and copy in the embed code they provide. If you need your videos to be
private (for example, if they are behind a paywall on your site), Vimeo
Pro offers great video hosting for this purpose.
Hosting your videos at YouTube also provides another point of
discovery, another place that can lead people to find you who otherwise
wouldn’t know about your site.
Chapter 7: Cloud Computing
What will you learn in this chapter?

 What cloud computing actually is


 The difference between IaaS, PaaS, and SaaS
 What your boss might mean about “getting on the cloud”
 What cloud hosting is, and why it doesn’t really matter

What is cloud computing?

Like a lot of popular words, “the Cloud” is as much a marketing


buzzword as it is a real concept. There really is such a thing as “cloud
computing,” and many web hosting companies are actively engaged in
providing cloud-based services, but the term itself can be a bit
misleading, and there isn’t really one single cloud that could be called
“the cloud.”
Cloud computing is a metaphor — a visual conception for us humans
that tries to communicate something hard to visualize. What the term is
trying to communicate is the idea of virtualized computing power riding
on top of clustered hardware, organized in such a fashion that computing
power itself because a utility, like electricity or water. The idea is that
you can use as much as you need, and pay for as much as you use. Much
like with the power grid or the water and sewer system, you aren’t
supposed to think too hard about where the electricity is coming from or
where your drain water goes — that is someone else’s job.
What people are talking about when they talk about the Cloud
A cloud works like this: a bunch of computers (servers) are clustered
together so that they can function as one giant computer. Virtual
computers are then deployed on top of that cluster.
From a marketing and business perspective, “cloud” could mean one of
several different things.

 Infrastructure as a Service — IaaS —This is what is happening


when a company owns actual hardware, a pool of clustered servers, and
can provide access to virtual machines, virtual drives, and other basic
computing resources from the larger pool.
 Platform as a Service — PaaS — Someone (who may own the
servers, or may be consuming infrastructure as a service from another
provider) runs operating systems and webservers on top of virtual
machines and provides them to others for their computing needs. This is
what a web hosting company is doing.
 Software as a Service — SaaS — Someone has built an application
for others to use, and hosts it on a platform they may or may not own.
Dropbox, Google Apps, and other subscription-based web applications
are an example of this.

Generally, “moving to the cloud” or doing something “in the cloud”


simply means storing data or running applications on someone else’s
clustered equipment. It means that they are consumers of either
Software, Platform, or Infrastructure as a Service.
Sometimes these three layers are owned by the same organization. Often
they are not.
The problem with “Cloud” as a metaphor
It’s easy to start thinking about the cloud as some ethereal mist of
computing resources — light, airy, and far above us. The problem with
this is that is very far away from the truth. Clouds are made up of
physical machines, with physical wires and physical disks.
This has a number of implications for how we use and consume cloud
services, but the biggest issue is security. If you are storing data on a
“cloud-based” data storage application, who has access to that data? Do
you even know where that data is, physically? It could be almost
anywhere, including in another country.
A better metaphor may be “pooled” or “clustered” computing, and even
better would be to say what is actually meant — whether that is
infrastucture, platform, or software as a service.

The Cloud and your business

Your boss has read some article in a magazine about how “Cloud
Computing” is the next big thing. Now you’re supposed to figure out
what that means and how to do it. How can you “take adavantage” of
this cloud computing trend?
You can either engage in cloud computing as a producer or a consumer,
or both.

Producer of Cloud Services

It is often said that in a gold rush, the people who sell shovels make
more money than the people who dig for gold.
This is true in reference to “the Cloud” as well — people who provide
some sort of cloud service are the biggest winners, and the more
fundamental the service, the larger the reward.
Providing IaaS or PaaS is a bit outside the realm of this guide and most
people reading it, but SaaS (software as a service) may not be.
If you sell software, it may be possible to re-imagine your application as
a SaaS offering. Rather than provide applications that clients have to run
on their own computers and servers, you may be able to provide access
to software through a web browser or web-connected desktop
application.
Consumer of Cloud Services

When most businesses (and marketing) talk about the advantages of


cloud computing, they are talking about the advantages of consuming
cloud services (platform or infrastructure) rather than producing
conventional computing power themselves.

 A company has traditionally used a desktop project management


system that shared data on a local server. They move to an online
application where users login from a web-browser. This is Software as a
Service.
 A web applications company that provides the SaaS project
management application has traditionally hosted the application on their
own server. They move to their application to a “Cloud Based” Virtual
Private Server at a hosting company. This is Platform as a Service.
 The hosting company doesn’t actually own any data centers, but
rather purchases raw computing power from Amazon Web Services.
This is Infrastructure as a Service.

These could all be described as forms of “cloud computing.”


The advantage in each is that something you may have previously been
required to purchase (at significant capital expense) can now be paid for
as it is used. This is especially economical if you don’t need the benefits
of an entire server yourself, or if you can’t afford the upfront expense.

Cloud Hosting

What does all of this have to do with web hosting?


Many web hosting companies sell some kind of “cloud hosting” plan.
This is usually a form of VPS hosting, where the VPS is sitting on top of
a cloud (cluster of computers) rather than directly on server hardware.
Many shared hosting plans work this way also, with dozens or hundreds
of hosting customers sharing a single VPS, which itself is one of many
on top of a pool of computing resources. The hosting company may or
may not own the hardware; they may create their own cloud
infrastructure, or consume it as a service from another provider.
The benefit to the customer is that cloud-based hosting (also called “grid
hosting” by some providers) is inherently scalable. Rather than a single
machine with storage, memory, and CPU limits, a virtual machine on a
cloud server has no hard physical limit. If activity spikes, it can use up a
larger percentage of the overall pool; if the pool becomes over-extended,
more hardware can be added to it.
Whether a hosting company bills its offerings as “cloud” or not
shouldn’t really be a concern for you as a web hosting customer. Most
web hosts are engaged in some form of clustering and virtualization, so
in some ways almost every hosting plan could be described as “cloud
based.” The term has a meaning, but as a marketing pitch it is almost
meaningless.
Chapter 8: Email, Webmail, and Mail Servers

More fundamental than running a website is the importance of reliable


email service. You have a number of options in how you set up your
own email service for your company. You’ll be better equipped to
choose the right option for yourself if you understand a little bit about
how it all works.

Email and domain names

As you almost certainly know, email addresses take the following form:
name@example.com
Everything before the @ sign is the local name, and everything after it is
the domain name.
It is a very bad practice, and unfortunately much too common, for small
organizations and sole practitioners to use a commercial email service
with a domain name like @gmail.com or@aol.com. This is a bad
practice because it looks unprofessional, amateurish.
It’s a very minor point, but it has a big impact on the way your clients
and potential customers think about you.
In an organization, such as a small business or (more commonly) a small
non-profit, the too-common practice of using personal email addresses
can introduce legal and ethical problems as well, because of the
inevitable mixing and confusion between personal and professional
communication. Also, email addresses controlled by the organization
can be turned off, blocked, forwarded to another address, or taken over
by another user.

Email servers and clients

Using email requires two things: an email server and an email client.
The email server is a piece of software that runs on the server
(computer) and is constantly connected to the internet. It receives and
processes any mail sent to it, and sends any mail you tell it to send.
The email client is the app you use to view your mail. This might be an
app on your phone, something you view in a web browser, or a desktop
application like Microsoft Outlook. The client checks the mail server for
new messages, and stores them for viewing. It provides an interface for
reading and writing messages. It sends outgoing messages to the server,
which sends them to their intended recipients.
The server and the client are two different pieces of software, and they
communicate using standardized protocols (POP and IMAP; see below).
This means that the choice of server and choice of client are independent
of each other.
People get confused about this all the time. One of the most often-heard
reasons people have for not wanting to switch from their personal email
addresses to organization-controlled email addresses is that they don’t
want to have to change how they read and write email. They use
Outlook, or Apple’s Email, and they think they will have to change. This
is not the case.
Most email clients can connect to most email servers with no problem.
Even better, most email clients can connect to multiple email servers and
work with multiple email accounts at the same time. This means that
someone who is using (for example) Outlook on their computer to check
their personal email account can set it up to check their professional
email as well.

Email protocols: POP  and IMAP

The two dominant email protocols are POP and IMAP. (A protocol is a


standardized way of moving information from one place to another.)
POP stands for “Post Office Protocol.” You will sometimes see it
written as “POP3,” because the protocol is in its third iteration.
IMAP stands for “Internet Message Access Protocol.”
Both are ways of moving message information from servers to clients,
but they are otherwise very different from each other.
POP is based on a “Post Office” model. The server delivers messages to
you, but does not otherwise keep them or store status information about
them. IMAP provides a high degree of syncing between the server and
the client.
You really want to be using IMAP most of the time. With IMAP, the
details of whether you have read a message, the content of drafts, and
other information about your own interaction with mail is saved on the
server. This means that your email experience is fully synced even if you
use multiple devices, like your laptop and your phone, to read the same
email.
When you are looking at web hosting plans, be sure to find one that
supports IMAP in the email server.

Ways to Access Email — Clients, Webmail

If you are running your email through the email server on your web
hosting account, you have a few different options about how to access it.
The “traditional” way is to use an email client application on your own
computer. This could be Outlook, Apple Mail, the mail client on your
phone, or another similar program.
Webmail is another option, provided by most web hosts. The client
application runs in your web browser and you access your email by
logging into your hosting account and then opening the Webmail page.
The two most popular webmail client applications are Squirrel Mail and
RoundCube. If you do not want to run a local client app, you should
check to see if your hosting account provides access to one of these two
applications. (Many offer both.)

Setting up a Client

Complete instructions on how to set up a client are a bit beyond the


purview of this guide, so I’ll just mention a couple things to get you
headed in the right direction.
Generally, your email client will have some kind of setup utility where
you can add email accounts to check. Each account will need a name,
server, password, and some information about the protocol.
The information you need to set this up is available from your web
hosting control panel. Somewhere near the interface where you setup
new email addresses and passwords, there will be a way to view
credentials. This will give you all the details you need for setting up the
account in your client. It is usually a very simple process.

Other Options

Some commercial webmail providers, like Gmail, will allow you to use
your webmail account as a client for another email address. This is a
good solution for people who want to add their domain-branded email
address into their current commercial personal email address inbox, and
check everything from the same place.
Another option is to outsource email altogether. Instead of running email
through the email server associated with your hosting account, you can
set up your DNS record to work with a commercial email provider (like
Google Apps, for example). With this setup, you get all the features and
user experience of the commercial email provider, with your own
domain name.
Finally, a very simple solution is to set up an email forwarder that sends
email to your branded email address on to whatever personal email
address you already have. This is a good solution for personal bloggers
and very small one-person businesses. The downside is that you will
always be replying from your personal email address.

Application Email

If you send occasional emails through your application (such as


registration emails, password recovery emails, invoices, receipts, and so
forth), this is not usually done through the mail server.
These types of messages are called “transactional email,” and are not
usually sent through your hosting account’s mail server, but rather sent
from the application code itself.
If the volume is excessive (such as might happen with a popular
ecommerce site), the application email becomes one more drain on a
hosting account’s resources. Additionally, some people will use
application email in low-cost shared hosting environments to send spam
email. Either of these situations (too much email, the wrong kind of
email) can affect your own application email.
If you are sending a lot of mission-critical transactional email, you may
want to look into outsourcing your application email to a premium
service. These usually work as plugins to your CMS or ecommerce
software.

Mailing Lists and Marketing Mail

Most shared hosting plans have specific Terms of Service prohibitions


against using your mail server or application mail capabilities to send
emails to large lists of people.
If you are using a VPS or dedicated server, you might not have an TOS
restrictions to stop you from doing this. Still, it isn’t a really good idea
(which is why shared servers plans don’t want you to do it).
The laws against spam email are very specific, and it isn’t a good idea to
try to figure out how to conform to them on your own. Additionally,
because of the wide number of variables that spam-blocking utilities
look at, the DIY approach can cause serious deliverability problems.
For most purposes, your best option for marketing mail is some kind of
commercial provider such as Mail Chimp or Aweber.

Summary
Business and organizations should use domain-branded email, and not
personal email addresses, for conducting business communication.
Email is sent to and received from the internet by a software application
called a mail server. The user reads and writes email from an application
called a mail client. The choice of each is independent of the choice of
the other.
Options for accessing email include local clients, webmail clients, and
using a commercial account as a client. Alternatively, you can outsource
it completely, associating your branded domain with a commercial email
provider.
Two side issues concerning email are application email and marketing
email.
Application email, or transactional email, is email sent from your site’s
application code, related to the functioning of the site itself. This is not
usually connected with your email server. Most of the time, you will not
need to worry or think about this kind of email — it just happens. If you
are sending a very large amount of it, you may want to look into
outsourced transactional email solutions.
Marketing email, such as newsletters sent to people who have signed up
to receive them, is subject to very strict laws as well as account Terms of
Service conditions. For this reason, a commercial provider of email
marketing services is usually the best option.
Protip: Use first and last names

A lot of organizations use weird patterns for translating individuals’


names into email address names. Most of these do not scale well.
If you use first names only, it will only be a matter of time before you
hire someone with a duplicate name. (I once worked for a company that
had three people named “Jeff,” along with a former employee and two
major customers also named “Jeff.”)
Other organizations do cute things like first initial plus last name. That
expands your pool a bit, but not enough. And it can be confusing and
hard to read. And it’s still only a matter of time before you have John
Doe and Jane Doe working in your organization.
When you have these name collisions, you end up with one person (the
first hired) to have the “canonical” version, and then the second person
is stuck with something like jsmith2 orjdoe1967.
This is not good.
While not completely perfect, I’m in favor of the
form firstname.lastname. This makes it much less likely you’ll have any
name collisions.
If you DO have a name collision, you should make both parties
usefirstname.middlename.lastname, or (if it makes more
sense),firstname.lastname.department. Having one person with the
standard version and the other one with the non-standard version
virtually guarantees that one of them will get the other one’s email on a
regular basis.
A lot of schools run into this problem with email addresses assigned to
students. I don’t really understand why it is such a common problem,
because it’s such an obvious and predictable issue to come up.
For schools, I recommend firstname.lastname.year, with year being
either the enrollment year or the graduation class year. (Four digits,
please.)
Chapter 9: Common Mistakes When Shopping for Web Hosting

This chapter focuses on a number of typical mistakes made by first-time


hosting buyers, and how to avoid them. It also pulls back the curtain on
a number of marketing tactics used by web hosting companies.

Buying on Price

There are two competing narratives offered by web hosting companies:

 All web hosting is basically the same, so buy the cheapest thing
you can find.
 Quality costs money so buy the most expensive hosting you can
afford.

Neither one of these is really accurate.


The discount hosting companies promote the idea that web hosting is
essentially a commodity, and so therefore price is the only thing that
really matters. They fall all over themselves to offer the cheapest
monthly rate, along with coupons and specials and discounts. It’s a race
to the bottom that no one really wins (least of all the customer).
There’s a grain of truth to this, of course — hardware is a relatively
cheap commodity, and most of the software used by web hosting
companies is free. Often, in measurable ways like CPU speed and
bandwidth, there isn’t much difference between a $3/month and a
$6/month host.
But the difference a few dollars can buy in terms of customer service
support and technical expertise is really quite outstanding.
Another thing to realize about discount web hosts is that the only way
they can afford to sell hosting for so cheap is to sell in volume and keep
people on board for a long time. This means several things:

 There will be more customers grouped onto a single shared server.


 There will be relatively little attention paid to individual issues,
because there are too many individuals to pay attention to.
 There will be incentives to pay for long-term contracts.
 There will be difficulties in moving or transferring.

The last one is especially troublesome, and seems to only come up with
shared hosting providers in the under-$5 range. They will make URL
transfer a complicated, multi-step process; they will provide no
instructions for unlocking or transferring domains anywhere in the help
files; they will require phone verification of cancellation; they will hide
buttons for dealing with transfer and cancellation under vaguely-named
menu labels; they will flood their FAQ and knowledge base with articles
about transferring to their service, to push “transfer away” articles down
the page in search engine results.
They say “you get what you pay for.” With discount web hosting you
often get a whole lot more on top of that.
Of course, on the other end of the spectrum is the “you’ll be so proud
that you could afford it” premium web hosting.
Sometimes this is deliberately over-priced for what it is — a hosting
company sells a fairly standard VPS plan and dresses it up with words
like “blazingly fast” and “white glove support” and charges twice as
much as a similar plan from another company.
More often, the problem is simply overselling. If you are running a
personal blog that will be read by a few hundred people, you probably
don’t need the Turbo-Charged Premium 3000X ClusterRack Edge
Server with Water-Cooled Multiplexing.
Exacerbating the marketing problem is the tendency of shoppers to
compare on price, and buy something in the middle. Part of the reason
for $2.50/month web hosting is that it makes the $5.50/month plan seem
like a reasonable mid-grade solution, rather than just another cheap
shared hosting plan.
A better approach is to figure out what type of hosting you need first
(see the chapter in this guide on Types of Web Hosting), and then look
for well-reviewed and highly-rated companies that offer that type of
plan.
If it comes down to two options that have very similar features and are
equally well-reviewed, then you can think about picking the cheaper one
to save a few dollars. But most of the time, once you get to the two or
three hosting companies and plans that will fit your needs, you’ll find
they are going to be priced very close to each other.
And if you really need to save a few dollars, use one of our coupons.

Paying attention to TV ads

TV commercials are extremely expensive, which means that a hosting


company that produces a lot of commercials isn’t spending that money
on technology or customer support.
Additionally, TV ads create an artificial sense of reputation. (“I’ve heard
of them — they must be good.”) This artificially inflated reputation
allows them to charge more than equally-good hosting companies
offering similar services.

Believing Affiliate Reviews

If you happen to come across an overly-positive review that suggests


that one particular host is the best option for all people, and it just
happens to have a link to the purchase page of the hosting company, you
can be completely sure that this is an affiliate marketing link.
Now — this is important — there is nothing wrong with affiliate
marketing or website reviews. (That’s what we do here at
WhoIsHostingThis, if you hadn’t noticed.)
However, it’s important to be objective at non-biased. Our reviews and
rating come from actual people talking about their actual experiences,
not us just saying a bunch of good things to get you to buy. Additionally,
we provide reviews, ratings, and information about hundreds of hosting
companies, not just the one with the high affiliate payout.
So what you want to watch out for as you are researching hosting
companies are websites that seem overly committed to one particular
hosting company, or where all the reviews are positive.

Buying based on bad features

There is a lot of free software available. Some of it is Open Source,


some of it is freeware, some of it is free trial versions of premium
software.
There is some amazing free software — WordPress, Drupal, Ruby on
Rails. But there is also an unbelievable amount of bad, free software.
Many web hosting companies make a bunch of this stuff available as a
free one click installation. You’re not really supposed to use all this stuff
— it’s a marketing ploy. They make it available so that they can say
“over 150 free software applications available with the purchase of a
hosting plan.”
Ignore this stuff. It isn’t useful software, but it also isn’t a bad sign if a
hosting company advertises this way. (That is: They all do it. Don’t
judge.)
Figure out what you specifically want to do — write a blog, run a
podcast, setup a wiki — and then find the software that will best serve
that purpose, and then find a host that supports it. Do not just randomly
pick a web hosting company and then browse their free app section and
start running your website on Free Page Web Creator Plus 1998.

Reading anything about SEO and webhosting

(Except this, of course.)


SEO — Search Engine Optimization — is always a hot topic, and the
people who are good at it are the ones you will find when you start
searching for information about it on a search engine (funny how that
works out). But a lot of the “SEO and Web hosting” content is barely
accurate at best.
There are continuous claims that sharing an IP in a shared hosting plan is
“bad for SEO.” (It mostly isn’t.) There are parallel claims that buying
some hosting feature will improve SEO. (It mostly won’t.)
And even if there is a tiny improvement for some of these things (getting
an HTTPS certificate is apparently beneficial), the difference will hardly
matter unless you are in a highly competitive niche — and then you’d
have to know about a thousand other things in addition to the rumor you
heard about Google penalizing sites hosted in the Central Time Zone.
SEO basics are very simple: Create a lot of good content and encourage
people to share and link to it. The most beneficial thing you can do from
a hosting standpoint is to go for speed — both search engines and
regular people prefer fast websites.

Вам также может понравиться