100
http://csetube.co.nr/ GKMCET Lecture Plan Subject Name: Web Technology Subject Code: IT2353 UNIT II Style Sheets: CSS 2.1 Introduction to Cascading Style Sheets Cascading Style Sheets (CSS) is a slightly misleading term, since a website might have only one CSS file (style sheet), or the CSS might be embedded within an HTML file. It is better to think of CSS as a technology (in the singular). CSS is comprised of statements that control the styling of HTML documents. Simply put, an HTML document should convey content. A CSS document should control the styling of that content. <div align="center"></div> <img src="this.gif" border="0" alt="" /> <table height="200">... <td width="30"></td> All these examples can easily be replaced with CSS. Don't worry if you don't understand these declarations yet. div {text-align: center;} img {border: 0 none;} table {height: 200px;} td {width: 30px;} An HTML file points to one or more external style sheets (or in some cases a list of declarations embedded within the head of the HTML file) which then controls the style of the HTML document. These style declarations are called CSS rules. 2.2 Features The latest version of Cascade Style Sheets, CSS 3, was developed to make Web design easier but it http://csetube.co.nr/

Web technology unit II

Embed Size (px)

Citation preview

Page 1: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

UNIT II

Style Sheets: CSS2.1 Introduction to Cascading Style Sheets

Cascading Style Sheets (CSS) is a slightly misleading term, since a website might have

only one

CSS file (style sheet), or the CSS might be embedded within an HTML file. It is better to

think

of CSS as a technology (in the singular). CSS is comprised of statements that control the

styling

of HTML documents. Simply put, an HTML document should convey content. A CSS

document

should control the styling of that content.

<div align="center"></div> <img src="this.gif" border="0" alt="" /> <table

height="200">... <td width="30"></td>

All these examples can easily be replaced with CSS. Don't worry if you don't understand

these

declarations yet.

div {text-align: center;} img {border: 0 none;} table {height: 200px;} td

{width: 30px;}

An HTML file points to one or more external style sheets (or in some cases a list of

declarations

embedded within the head of the HTML file) which then controls the style of the HTML

document. These style declarations are called CSS rules.

2.2 Features

The latest version of Cascade Style Sheets, CSS 3, was developed to make Web design

easier but it

http://csetube.co.nr/

Page 2: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

became a hot topic for a while because not all browsers supported it. However, trends

change quickly in

technology and all browser makers currently are implementing complete CSS 3 support.

Making that

process easier for the browser manufacturers is CSS 3's modularized specification, which

allows them to

provide support for modules incrementally without having to perform major refactoring

of the browsers'

codebases. The modularization concept not only makes the process of approving

individual CSS 3

modules easier and faster, but it also makes documenting the spec easier.

Eventually, CSS 3 -- along with HTML5 -- are going to be the future of the web. You

should begin

making your Web pages compatible with these latest specifications. In this article, I

explore 10 of the

exciting new features in CSS 3, which is going to change the way developers who used

CSS2 build

websites.Some of the features are:

o CSS Text Shadow

o CSS Selectors

o CSS Rounded Corners

o CSS Border Image

3 Core Syntax

2.3.1 At-Rules

As we learned when we studied CSS statements, there are two types of statements. The

most

common is the rule-sets statement, and the other is the at-rules statement. As opposed to

rule

http://csetube.co.nr/

Page 3: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

sets, at-rules statements consist of three things: the at-keyword, @, an identifier, and a

declaration. This declaration is defined as all content contained within a set of curly

braces, or by

all content up until the next semicolon.

@import

Perhaps the most commonly used of the at-rules, @import, is used to import an external

style

sheet into a document. It can be used to replace the LINK element, and serves the same

function,

except that imported style sheets have a lower weight (due to having less proximity) than

linked

style sheets.

<style type="text/css" media="screen"> @import url(imported.css); </style>

@import url(addonstyles.css); @import "addonstyles.css";

Relative and absolute URLs are allowed, but only one is allowed per instance of

@import. One

or more comma-separated target media may be used here.

@charset

@charset is used to specify the character encoding of a document, and must appear no

more than

once. It must be the very first declaration in the external style sheet, and cannot appear in

embedded style sheets. @charset is used by XML documents to define a character set.

@charset "utf-8";

@namespace

The @namespace rule allows the declaration of a namespace prefix to be used by

selectors in a

style sheet. If the optional namespace prefix is omitted, then the URL provided becomes

the

http://csetube.co.nr/

Page 4: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

default namespace. Any @namespace rules in a style sheet must come after all @import

and

@charset at-rules, and come before all CSS rule-sets.

@namespace foo url("http://www.example.com/");

@namespace can be used together with the new CSS3 selectors (see below). It defines

which

XML namespace to use in the CSS. If the XML document doesn't have matching XML

namespace information, the CSS is ignored.

@font-face

This was removed from the CSS2.1 specification, but is still used to describe a font face

for a

document..

@font-face { font-family: "Scarborough Light"; src:

url("http://www.font.com/scarborough-lt"); } @font-face { font-family:

Santiago; src: local ("Santiago"), url("http://www.font.com/santiago.tt"),

format("truetype"); unicode-range: U+??,U+100-220; font-size: all; fontfamily:

sans-serif; }

@media

This at-rule is used within a style sheet to target specific media. For example, after

defining how

an element is to be displayed (in this example for the screen), the declaration can be

overwritten

for print, in which case we often want to hide navigation.

p {font-size: 0.8em;} /* for the screen */ @media print { p {font-size:

10pt;} #nav, #footer {display: none;} } @media screen, handheld { p {fontsize:

14px; text-align: justify;} }

The media types are as follows.

all

http://csetube.co.nr/

Page 5: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

aural (for speech synthesizers)

handheld

print

projection

screen

braille

embossed

tty

tv

@page

This at-rules declaration is used to define rules for page sizing and orientation rules for

printing.

@page {size: 15cm 20cm; margin: 3cm; marks: cross;}

You may specify how pages will format if they are first, on the left-hand side, or on the

right.

@page :first {margin-top: 12cm;} @page :left {margin-left: 4.5cm;} @page

:right {margin-right: 7cm;}

@fontdef

This is an old Netscape-specific at-rule which we should ignore.

CSS1 Selectors

Selectors refer to elements in an HTML document tree. Using CSS, they are pattern-

matched in

http://csetube.co.nr/

Page 6: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

order to apply styles to those elements. A selector consists of one or more elements,

classes, or

IDs, and may also contain pseudo-elements and/or pseudo-classes.

Type Selector

The type selector is the simplest selector of all, and matches all occurrences of an

element. In

this example, all <p> tags throughout the document will have the following style applied,

unless

overridden.

p {color: #666;}

Universal Selector

The universal selector, used alone, matches all elements in the document tree, and thus

will apply

styles to all elements. It is in effect a wildcard.

* {margin: 0; padding: 0;}

In this example, all tags are reset to have no padding or margin. This, by the way, is a

practice to

gain control over all the default padding and margin inherent in the way User Agents

(UAs)

display HTML.

Class Selector

The class selector matches a classname.

.largeFont {font-size: 1.5em;} h3.cartHeader {text-align: center;}

The "largeFont" class will apply to all elements into which it is called. The "cartHeader"

class

will only function as styled if called into an H3 element. This is useful if you have

another

http://csetube.co.nr/

Page 7: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

"cartHeader" declaration that you wish to override in the context of an H3 element, or if

you

wish to enforce the placement of this class.

ID Selector

The ID selector matches an ID. IDs are identifiers unique to a page. They bear a

resemblance to

classes, but are used a bit differently. IDs will be treated more fully below. The first two

ID

examples below refer to sections of a web page, while the last refers to a specific

occurrence of

an item, say, an image in a DHTML menu. IDs have a higher specificity than classes.

#header {height: 100px;} #footer {color: #F00;} #xyz123 {font-size: 9px;}

Descendant Selector

A selector can itself be a chain of one or more selectors, and is thus sometimes called a

compound selector. The descendant selector is the only compound selector in CSS1, and

consists

of two or more selectors and one or more white space combinators. In the example

below, the

white space between the H1 and EM elements is the descendant combinator. In other

words,

white space conveys a hierarchy. (If a comma were to have intervened instead, it would

mean

that we were styling H1 and EM elements alike.) Selectors using combinators are used

for more

precise drill-down to specific points within the document tree. In this example <em> tags

will

have the color red applied to them if they are within an <h1> tag.

h1 em {color: #F00;}

http://csetube.co.nr/

Page 8: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Note that EM elements do not have to be immediately inside an H1 heading, that is, they

do not

have to be children, but merely descendants of their ancestor. The previous style would

apply to

an EM element in either of the following statements.

<h1>This is a <em>main</em> heading</h1> <h1>This is <strong>another

<em>main</em> heading</strong></h1>

In the next example, the color black will be applied to all <span> tags that are

descendants

(whether directly or not) of <div> tags which are in turn descendants (whether directly or

not) of

<p> tags, no matter how deep the <p> tags are in the document tree.

div p span {color: #000;}

That is to say, this style would apply to SPAN elements inside a P element, even if they

are

many levels below (that is, within) the DIV element, as long as there is an intervening P

element.

The universal selector can be part of a compound selector in tandem with a combinator.

p * span {font-size: 0.6em;}

This would style any SPAN element that is at least a grandchild of a P element. The

SPAN

element could in fact be much deeper, but it will not be styled by this declaration if it is

the child

(direct descendant) of a P element.

Other Selectors

Other combinators convey greater precision. They include the direct adjacent sibling

combinator

http://csetube.co.nr/

Page 9: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

(+), the indirect adjacent sibling (or general) combinator (~), and the child combinator

(>). These

combinators will be treated below because they are part of the CSS2.1 specification, and

are not

supported in IE6.

EXAMPLE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0

Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<style type="text/css">

div.ex

{

width:220px;

padding:10px;

border:5px solid gray;

margin:0px;

}

</style>

</head>

2.4 STYLE SHEETS AND HTML STYLE RULE

To apply a style, CSS uses the HTML document tree to match an element, attribute, or

value in

an HTML file. For an HTML page to properly use CSS, it should be well-formed and

valid, and

possess a valid doctype. If these conditions are not met the CSS match may not yield the

desired

http://csetube.co.nr/

Page 10: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

results.There are two types of CSS statements: rule-sets and at-rules. A rule set, also

known

simply as a rule, is the more common statement, and consists of a selector and a

declaration

block, sometimes simply called a block. The selector can be an element, class, or ID, and

may

include combinators, pseudo-elements, or pseudo-classes.

Statement Type 1: Rules Sets (Rules)

statement + statement block

X {declaration; declaration;}

X {property; value; property: value;}

div > p {font-size: 1em; color #333;}

Statement Type 2: At-Rules

at-keyword + identifier + declaration

@import "subs.css";

The declaration block consists of the braces and everything in between. Within the

declaration

block are declarations, which consist of properties and values. Properties are separated

from their

values (also known as styles) by colons, and declarations are delimited by semi-colons.

(Properties are also known as attributes, but that terminology is not used in this document

lest we

confuse CSS properties with HTML attributes.) White space inside a declaration block is

ignored, which facilitates formatting the code in developer-friendly ways. For example,

both of

the following statements are valid and equivalent, though the latter slightly increases

document

weight.

http://csetube.co.nr/

Page 11: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

h1 {color: blue; margin-top: 1em;} h1 { color: blue; margin-top: 1em; }

Ensure, however, that there is no white space between a value and its unit of

measurement (e.g.

1.2em, not 1.2 em).As opposed to rule sets, at-rules statements consist of the at-keyword

"@", an

identifier, and a declaration. This declaration is defined as all the content contained

within a set

of curly braces, or by all content up until the next semicolon. Note the following two

examples.

@media print { p {font-size: 10pt;} tt {font-family: monospace;} } @import

url(addonstyles.css);

Other examples of at-keywords are media, font-face, and page. At-rules will be treated

separately

below.

Properties

I have decided not to include a description of all CSS1 and CSS2.1 Properties (such as

font-size,

text-transform, border, margin, and many others) because they are numerous and can be

examined in the Property References section of this site. Moreover, they are used

throughout this

tutorial and can be easily deduced. So we move directly to CSS1 selectors.

1.5 STYLE RULE CASCADING AND INHERITANCE

CSS are probably wondering what exactly cascades about cascading style sheets. In this

section

we look at the idea of cascading, and a related idea, that of inheritance. Both are

important

underlying concepts that you will need to grasp, and understand the difference between,

in order

http://csetube.co.nr/

Page 12: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

to work properly with style sheets.

Rule Cascade

A single style sheet associated with one or more web pages is valuable, but in quite a

limited

way. For small sites, the single style sheet is sufficient, but for larger sites, especially

sites

managed by more than one person (perhaps several teams who may never communicate)

single

style sheets don't provide the ability to share common styles, and extend these styles

where

necessary. This can be a significant limitation.

Cascading style sheets are unlike the style sheets you might have worked with using word

processors, because they can be linked together to create a hierarchy of related style

sheets.

Managing style at large sites using @import

Imagine how the web site for a large organization, say a corporation, might be structured.

As

sites grow in complexity, individual divisions, departments, and workgroups become

more

responsible for their own section of a site. We can already see a potential problem - how

do we

ensure a consistent look and feel across the whole site?A dedicated web development

team can

ensure that a style guide is adhered to.

Specificity

Get browser support information for specificity in the downloadable version of this guide

or our

http://csetube.co.nr/

Page 13: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

browser support tables.At this point it might be timely to have a quick discussion of

specificity.

Both inside a single style sheet, and in a cascade of style sheets, it should be clear that

more than

one rule can apply to the same element. What happens when two properties in separate

rules

which both apply to an element contradict one another? Obviously they can't both apply

(the text

of an element can't be both red and blue, for example). CSS provides a mechanism for

resolving

these conflicts, called specificity.

Some selectors are more specific than others. For example, the class and ID selectors are

more

specific than simple HTML element selectors. When two rules select the same element

and the

properties contradict one another, the rule with the more specific selector takes

precedence.

Specificity for selectors is a little involved. Without going into the full detail, most

situations can

be resolved with the following rules.

1. ID selectors are more specific than other selectors

2. Class selectors are more specific than HTML element selectors, and other selectors

such

as contextual, pseudo class and pseudo element selectors.

3. Contextual selectors, and other selectors involving more than one HTML element

selector are more specific than a single element selector (and for two multiple element

selectors, the one with more elements is more specific than the one with fewer.)

http://csetube.co.nr/

Page 14: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

There are times though when the two rules will have the same specificity. In this case, the

rule

that comes later in the cascade prevails.For example, where one rule is in an imported

style

sheet, and the other in the style sheet itself, the rule in the style sheet which is importing

takes

precedence. When the two rules are in the same style sheet, it is the one furthest from the

top of

the style sheet that takes precedence.While these rules seem complicated at first, they are

pretty

much common sense, and it is uncommon that much confusion or difficulty arises for a

developer.

Style Inheritance

Any HTML page comprises a number of (perhaps a large number of) elements -

headings,

paragraphs, lists, and so on. Often, developers use the term "tag" to refer to an element,

making

reference for example to "the p tag". But the tag is simply the <p></p> part of the

element. The

whole construction of <p>This is the content of the paragraph</p> is in fact the <p>

element (as we refer to it in this guide). What many web developers don't realize (largely

because it wasn't particularly important until style sheets came along) is that every

element is

contained by another element, and may itself contain other elements. The technical term

for this

is the containment hierarchy of a web page.

At the top of the containment hierarchy is the <html> element of the page. Every other

element

http://csetube.co.nr/

Page 15: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

on a web page is contained within the <html> element, or one of the elements contained

within

it, and so on. Similarly, many elements will be contained in paragraphs, while paragraphs

are

contained in the <body>.

Graphically, we can understand it like this.

figure 4: the HTML containment hierarchy

I said above that style sheets made it important to understand this. Why? Well, with

cascading

style sheets, elements often (and with CSS2 can always be forced to) inherit properties

from the

elements which contain them (otherwise known as their parent elements). This means

that if you

give the body of the page certain properties (for example font and color) then every

element

within the page will inherit these properties- there is no need to set the font and color

again for

each element, such as list items or paragraphs.

You can always override the inheritance however. By assigning a property to an element,

you

override the inherited property.

2.6 Text t properties

2.6.1 CSS Font Families

CSS font properties define the font family, boldness, size, and the style of a text.

Difference Between Serif and Sans-serif Fonts

On computer screens, sans-serif fonts are considered easier to read than serif fonts.

In CSS, there are two types of font family names:

http://csetube.co.nr/

Page 16: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

generic family - a group of font families with a similar look (like "Serif" or

"Monospace")

font family - a specific font family (like "Times New Roman" or "Arial")

Generic family Font family Description

Serif

Times New Roman

Georgia

Serif fonts have small lines at the ends on some

characters

Sans-serif

Arial

Verdana

"Sans" means without - these fonts do not have the

lines at the ends of characters

Monospace

Courier New

Lucida Console

All monospace characters have the same width

Font Family

The font family of a text is set with the font-family property.The font-family property

should

hold several font names as a "fallback" system. If the browser does not support the first

font, it

tries the next font.Start with the font you want, and end with a generic family, to let the

browser

pick a similar font in the generic family, if no other fonts are available.

Note: If the name of a font family is more than one word, it must be in quotation marks,

like

http://csetube.co.nr/

Page 17: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

font-family: "Times New Roman".More than one font family is specified in a comma-

separated

list:

Example

p{font-family:"Times New Roman", Times, serif;}

Font Style

The font-style property is mostly used to specify italic text.

This property has three values:

normal - The text is shown normally

italic - The text is shown in italics

oblique - The text is "leaning" (oblique is very similar to italic, but less supported)

Example

p.normal {font-style:normal;}

p.italic {font-style:italic;}

p.oblique {font-style:oblique;}

Font Size

The font-size property sets the size of the text.Being able to manage the text size is

important in

web design. However, you should not use font size adjustments to make paragraphs look

like

headings, or headings look like paragraphs.Always use the proper HTML tags, like <h1>

- <h6>

for headings and <p> for paragraphs.

The font-size value can be an absolute, or relative size.

Absolute size:

Sets the text to a specified size

Does not allow a user to change the text size in all browsers (bad for accessibility

reasons)

http://csetube.co.nr/

Page 18: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Absolute size is useful when the physical size of the output is known

Relative size:

Sets the size relative to surrounding elements

Allows a user to change the text size in browsers

If you do not specify a font size, the default size for normal text, like paragraphs, is 16px

(16px=1em).

Set Font Size With Pixels

Setting the text size with pixels, gives you full control over the text size:

Example

h1 {font-size:40px;}

h2 {font-size:30px;}

p {font-size:14px;}

Set Font Size With Em

To avoid the resizing problem with Internet Explorer, many developers use em instead of

pixels.The em size unit is recommended by the W3C.1em is equal to the current font size.

The

default text size in browsers is 16px. So, the default size of 1em is 16px.

The size can be calculated from pixels to em using this formula: pixels/16=em

Example

h1 {font-size:2.5em;} /* 40px/16=2.5em */

h2 {font-size:1.875em;} /* 30px/16=1.875em */

p {font-size:0.875em;} /* 14px/16=0.875em */

All CSS Font Properties

The number in the "CSS" column indicates in which CSS version the property is defined

(CSS1

or CSS2).

Property Description Values CSS

font

http://csetube.co.nr/

Page 19: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Sets all the font

properties in one

declaration

font-style

font-variant

font-weight

font-size/line-height

font-family

caption

icon

menu

message-box

small-caption

status-bar

1

inherit

font-family

Specifies the font family

for text

family-name

generic-family

inherit

1

font-size

Specifies the font size of

text

xx-small

x-small

http://csetube.co.nr/

Page 20: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

small

medium

large

x-large

xx-large

smaller

larger

length

%

inherit

1

font-style

Specifies the font style

for text

normal

italic

oblique

inherit

1

font-variant

Specifies whether or not

a text should be

displayed in a small-caps

font

normal

small-caps

inherit

1

http://csetube.co.nr/

Page 21: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

font-weight

Specifies the weight of a

font

normal

bold

bolder

lighter

100

200

300

400

500

600

700

800

900

1

inherit

Text Formatting and color

All CSS Text Properties

The number in the "CSS" column indicates in which CSS version the property is defined

(CSS1

or CSS2).

Property Description Values CSS

color Sets the color of a text color 1

direction Sets the text direction

ltr

rtl

http://csetube.co.nr/

Page 22: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

2

line-height Sets the distance between lines

normal

number

length

%

1

letter-spacing Increase or decrease the space between characters

normal

length

1

text-align Aligns the text in an element

left

right

center

justify

1

text-decoration Adds decoration to text

none

underline

overline

line-through

blink

1

text-indent Indents the first line of text in an element

length

%

1

http://csetube.co.nr/

Page 23: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

text-shadow

none

color

length

text-transform Controls the letters in an element

none

capitalize

uppercase

lowercase

1

unicode-bidi

normal

embed

bidi-override

2

vertical-align Sets the vertical alignment of an element

baseline

sub

super

top

text-top

middle

bottom

text-bottom

length

%

1

white-space Sets how white space inside an element is handled

http://csetube.co.nr/

Page 24: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

normal

pre

nowrap

1

word-spacing Increase or decrease the space between words

normal

length

1

2.7 The CSS Box Model

BLOCK DIAGRAM

All HTML elements can be considered as boxes. In CSS, the term "box model" is used

when

talking about design and layout.

The CSS box model is essentially a box that wraps around HTML elements, and it

consists of:

margins, borders, padding, and the actual content.

The box model allows us to place a border around elements and space elements in

relation to

other elements.

The image below illustrates the box model:

Explanation of the different parts:

Margin - Clears an area around the border. The margin does not have a background color,

it is

completely transparent

Border - A border that goes around the padding and content. The border is affected by the

background color of the box

Padding - Clears an area around the content. The padding is affected by the background

color of

http://csetube.co.nr/

Page 25: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

the box

Content - The content of the box, where text and images appear

In order to set the width and height of an element correctly in all browsers, you need to

know

how the box model works.

Width and Height of an Element

Important: When you specify the width and height properties of an element with CSS,

you are

just setting the width and height of the content area. To know the full size of the element,

you

must also add the padding, border and margin.

The total width of the element in the example below is 300px:

width:250px;

padding:10px;

border:5px solid gray;

margin:10px;

Let's do the math:

250px (width)

+ 20px (left and right padding)

+ 10px (left and right border)

+ 20px (left and right margin)

= 300px

Imagine that you only had 250px of space. Let's make an element with a total width of

250px:

Example

width:220px;

padding:10px;

border:5px solid gray;

http://csetube.co.nr/

Page 26: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

margin:0px;

The total width of an element should always be calculated like this:

Total element width = width + left padding + right padding + left border + right border +

left

margin + right margin

The total height of an element should always be calculated like this:

Total element height = height + top padding + bottom padding + top border + bottom

border +

top margin + bottom margin

Example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>

<style type="text/css">

div.ex

{

width:220px;

padding:10px;

border:5px solid gray;

margin:0px;

}

</style>

</head>

CSS Background

CSS background properties are used to define the background effects of

an element.

CSS properties used for background effects:

http://csetube.co.nr/

Page 27: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

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 defined in the body selector:

Example

body {background-color:#b0c4de;}

The background color can be specified by:

name - a color name, like "red"

RGB - an RGB value, like "rgb(255,0,0)"

Hex - a hex value, like "#ff0000"

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

almost not

readable:

Background Image - Repeat Horizontally or Vertically

By default, the background-image property repeats an image both horizontally and

vertically.

http://csetube.co.nr/

Page 28: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Some images should be repeated only horizontally or vertically, or they will look strange,

like

this:

Example

body

{

background-image:url('gradient2.png');

}

If the image is repeated only horizontally (repeat-x), the background will look better:

Example

body

{

background-image:url('gradient2.png');

background-repeat:repeat-x;

}

Background Image - Set position and no-repeat

When using a background image, use an image that does not disturb the text.

Showing the image only once is 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

http://csetube.co.nr/

Page 29: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

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 - Shorthand property

As you can see from the examples above, there are many properties to consider when

dealing

with backgrounds.

To shorten the code, it is also possible to specify all the properties in one single property.

This is

called a shorthand property.

The shorthand property for background is simply "background":

body {background:#ffffff url('img_tree.png') no-repeat right top;}

When using the shorthand property the order of the property values are:

background-color

background-image

background-repeat

background-attachment

background-position

It does not matter if one of the property values are missing, as long as the ones that are

present

are in this order.

This example uses more advanced CSS. Take a look: Advanced example

All CSS Background Properties

http://csetube.co.nr/

Page 30: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

The number in the "CSS" column indicates in which CSS version the property is defined

(CSS1

or CSS2).

Property Description Values CSS

background

Sets all the background properties

in one declaration

background-color

background-image

background-repeat

background-attachment

background-position

inherit

1

background-attachment

Sets whether a background image is

fixed or scrolls with the rest of the

page

scroll

fixed

inherit

1

background-color

Sets the background color of an

element

color-rgb

color-hex

color-name

http://csetube.co.nr/

Page 31: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

transparent

inherit

1

background-image

Sets the background image for an

element

url(URL)

none

inherit

1

background-position

Sets the starting position of a

background image

left top

left center

left bottom

right top

right center

right bottom

center top

center center

center bottom

x% y%

xpos ypos

inherit

1

background-repeat

Sets if/how a background image will

http://csetube.co.nr/

Page 32: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

be repeated

repeat

repeat-x

repeat-y

no-repeat

inherit

1

2.8 NORMAL FLOW BOX LAYOUT

Understanding the box model is critical to developing web pages that don't rely on tables

for

layout. In the early days of writing HTML, before the advent of CSS, using tables was

the only

way to have discreet content in separate boxes on a page. But tables were originally

conceived to

display tabular information. With the advent of CSS floating and positioning, there is no

longer a

need to use tables for layout, though many years later many, if not most, sites are still

using

tables in this manner.The box model, as defined by the W3C "describes the rectangular

boxes

that are generated for elements in the document tree and laid out according to the visual

formatting model". Don't be confused by the term "boxes". They need not appear as

square boxes

on the page. The term simply refers to discreet containers for content. In fact, every

element in a

document is considered to be a rectangular box.

Padding, Borders, Margins

http://csetube.co.nr/

Page 33: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Padding immediately surrounds the content, between content and borders. A margin is

the space

outside of the borders. If there are no borders both paddng and margin behave in roughly

the

same way, except that you can have negative margins, while you cannot have negative

padding.

Also padding does not collapse like margins. See below for the section on collapsing

margins.

The picture on the right illustrates padding, borders, and margins. The content area does

not

really have a border. The line around the content merely indicates the limits of the actual

content.

Traditional vs. W3C Box Models

So how do you declare these properties in your CSS, and how do you set the width of a

box?

That depends on the box model. There are actually two box models. The traditional box

model is

supported by IE5.5 and previous versions of IE, and any version of IE in quirks mode. It

states

that the width of a box is the combined width of the content, its padding and its borders.

Imagine

a literal box that you can hold. The carboard exterior is the border. We don't care about

the

content inside of the box. It may fill up the box entirely or have space around it. If it has

space

around it, that is its padding, which sits between the content and the exterior (border) of

the box.

http://csetube.co.nr/

Page 34: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

But according to this model, it does not matter what the actual content width is. The

width of the

box is what matters. Using the traditional model let's consider the following declaration.

.box {width: 200px; border: 1px solid black; padding: 10px;}

In the traditional model the width of the box is 200 pixels.

CSS: .wrap {width: 760px;} .menu {float: left; width 187px; padding: 6px;

border-right: 1px solid #999;} .main {float: left; width 548px; padding:

6px;} HTML: <div id="wrap"> <div id="menu"></div> <div id="main"></div>

</div>

The math from left to right would be:menu left padding + menu content + menu right

padding +

menu border + main left padding + main content + main right padding (or in pixels) 6 +

187 + 6

+ 1 + 6 + 548 + 6 = 760.

Margin Collapse

Vertical margins collapse when they meet. Though it may seem like a strange thing, if

you have

assigned top and bottom margins to the P element of, say, 10px each, you will not have

20px of

margin between paragraphs, but rather 10px. This is considered to be desirable and

expected

behavior, and not a bug. Now consider the following declaration.

p {margin: 10px 0 16px;}

In this case the space between paragraphs would be 16px, that is, the greater of the two

values.

Margin collapse does not occur when either box is floated, when one element uses the

overflow

http://csetube.co.nr/

Page 35: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

property set to any value other than "visible", with absolutely positioned elements, with

elements

whose display property is set to "inline-block", or if the child element is cleared.You can

override margin collapse also by adding a border, of the same color as the background if

you

want it unnoticed, or by using padding instead of margins. Eric Meyer has a nice

description of

collapsing margins. In sum, margin collapse is meant to prevent certain design problems,

and yet

is not difficult to override.

Display Property

This is one of the most useful properties. The complete list of values is in the appendix of

this

document, but the most useful ones follow.

block

Block display provides behavior similar to a default DIV element. A line break occurs at

the

close of the tag. Elements that are block by default are DIV, P, BLOCKQUOTE, H1

through H6,

UL, OL, LI, ADDRESS, etc. Block elements accept width, height, top and bottom

margins, and

top and bottom padding. A block element constitutes a separate block box.

inline

Inline display creates no such line break. Elements that are inline by default are SPAN,

IMG,

INPUT, SELECT, EM, STRONG, etc. Inline elements do not accept width, height, top

and

http://csetube.co.nr/

Page 36: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

bottom padding, and top and bottom margins, which makes good sense, since they are

used for

part of a line of text (i.e. of a block box).

They do, however, accept left and right padding, left and right margins, and line-height.

Lineheight

can then be used to approximate height. If you need to apply width, height or other block

properties to an inline element, consider assigning the element block display and/or

floating it.

Block display, of course, will force the element on to a separate line (unless the element

is

floated). Alternatively you can assign the inline-block value to make an inline element

take block

properties (see below).

none

Display set to none sets the element to invisible similar to the hidden value of the

visibility

property (see below). However, unlike the visibility property, this value takes up no space

on the

page. This is very useful for DHTML hidden tools and for other instances when you need

items

to expand and collapse based on whether they contain content to be viewed on demand.

Moreover, when you generate content, items whose display is set to none will not be

included in

the loop. (For more on generated content, see below.) Display set to none will also be

hidden

from most screen readers. If you are trying to make something readable only for those

with sight

disabilities, use an off-screen class like this:

http://csetube.co.nr/

Page 37: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

.offScreen {position: absolute; left: -10000px; top: auto; width: 1px;

height: 1px; overflow: hidden;}

inline-block

This value causes the element to generate a block element box that will be flowed with

surrounding content as if it were a single inline box. It lets you place a block inline with

the

content of its parent element. It also allows you to assign properties associated with block

display, such as width and height to an element that naturally takes inline display. This

property

is also used to trigger hasLayout in IE6, which is a difficult concept, but briefly means

making

IE6 assume CSS certain properties.

run-in

This display mode causes the element to appear as an inline element at the start of the

block

immediately following it. If there is no block following a run-in element, it is displayed

as a

normal block instead. Currently, there seems to be no browser support for this value

except for

IE8, but here is an example of how it is coded, and how it should look.

<div style="display: run-in">Here is some run-in text on this line.</div>

<div style="display: block">But here is a block that follows it, so they are

conjoined.</div>

Let's seer if it works. Here is some run-in text on this line.But here is a block that follows

it, so

are they conjoined? Well, apparently not in Firefox. Oh well.

list-item

http://csetube.co.nr/

Page 38: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Unordered lists are traditionally used to list bulleted items vertically. But you can assign

bullets

to other elements using the list-item value.

div {display: list-item;}

It may not make a lot of semantic sense to apply bullets to an element that is not a list

item, but

at the very least it's helpful that CSS is so flexible. However you use these values, ensure

that

your HTML is meaningful irrespective of your CSS. Because there is a wide variety of

display

values, HTML tags can be made to display in a variety of ways, some counter to the

nature of the

element. Care should be taken to maintain the implicit content of elements. Should you,

for

example, give a P element inline display? You can, but use caution. It is more likely that

you will

set the inline value for the DIV element. This seems to be more acceptable in that the

DIV

element simply provides separate treatment for content, while a paragraph is visually

demarcated

from other elements.

2.9 Beyond the Normal Flow

Positioning

The CSS positioning properties allow you to position an element. It can also place an

element

behind another, and specify what should happen when an element's content is too

big.Elements

http://csetube.co.nr/

Page 39: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

can be 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

positioning method.There are four different positioning methods.

Static Positioning

HTML elements are positioned static by default. A static positioned element is always

positioned

according to the normal flow of the page.Static positioned elements are not affected by

the top,

bottom, left, and right properties.

Fixed Positioning

An element with fixed position is positioned relative to the browser window.It will not

move

even if the window is scrolled:

Example

p.pos_fixed

{

position:fixed;

top:30px;

right:5px;

}

Note: Internet Explorer supports the fixed value only if a !DOCTYPE is specified.Fixed

positioned elements are removed from the normal flow. The document and other

elements

behave like the fixed positioned element does not exist.Fixed positioned elements can

overlap

other elements.

http://csetube.co.nr/

Page 40: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Relative Positioning

A relative positioned element is positioned relative to its normal position.

Example

h2.pos_left

{

position:relative;

left:-20px;

}

h2.pos_right

{

position:relative;

left:20px;

}

The content of a relatively positioned elements can be moved and overlap other elements,

but the

reserved space for the element is still preserved in the normal flow.

Example

h2.pos_top

{

position:relative;

top:-50px;

}

Relatively positioned element are often used as container blocks for absolutely positioned

elements.

Absolute Positioning

An absolute position element is positioned relative to the first parent element that has a

position

other than static. If no such element is found, the containing block is <html>:

http://csetube.co.nr/

Page 41: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Example

h2

{

position:absolute;

left:100px;

top:150px;

}

27

Absolutely positioned elements are removed from the normal flow. The document and

other

elements behave like the absolutely positioned element does not exist.Absolutely

positioned

elements can overlap other elements.

Overlapping Elements

When elements are positioned outside the normal flow, they can overlap other

elements.The zindex

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:

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.

http://csetube.co.nr/

Page 42: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

All CSS Positioning Properties

The number in the "CSS" column indicates in which CSS version the property is defined

(CSS1

or CSS2).

Property Description Values CSS

bottom

Sets the bottom margin edge for a

positioned box

auto

length

%

inherit

2

clip Clips an absolutely positioned element

shape

auto

inherit

2

cursor Specifies the type of cursor to be displayed

url

auto

crosshair

default

pointer

move

2

28

e-resize

http://csetube.co.nr/

Page 43: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

ne-resize

nw-resize

n-resize

se-resize

sw-resize

s-resize

w-resize

text

wait

help

left

Sets the left margin edge for a positioned

box

auto

length

%

inherit

2

overflow

Specifies what happens if content overflows

an element's box

auto

hidden

scroll

visible

inherit

2

position

http://csetube.co.nr/

Page 44: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Specifies the type of positioning for an

element

absolute

fixed

relative

static

inherit

2

right

Sets the right margin edge for a positioned

box

auto

length

%

inherit

2

top

Sets the top margin edge for a positioned

box

auto

length

%

inherit

2

z-index Sets the stack order of an element

number

auto

inherit

http://csetube.co.nr/

Page 45: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

2

29

What is CSS Float?

With CSS float, an element can be pushed to the left or right, allowing other elements to

wrap around it.

Float is very often used for images, but it is also useful when working with layouts.

How Elements Float

Elements are floated horizontally, this means that an element can only be floated left or

right, not

up or down.A floated element will move as far to the left or right as it can. Usually this

means all

the way to the left or right of the containing element.The elements after the floating

element will

flow around it.The elements before the floating element will not be affected.

If an image is floated to the right, a following text flows around it, to the left:

Example

img

{

float:right;

}

Floating Elements Next to Each Other

If you place several floating elements after each other, they will float next to each other if

there

is room.Here we have made an image gallery using the float property:

Example

.thumbnail

{

float:left;

http://csetube.co.nr/

Page 46: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

width:110px;

height:90px;

margin:5px; }

2.10 SOME OTHER USEFUL STYLE PROPERTIES

CSS Lists

The CSS list properties allow you to:

o Set different list item markers for ordered lists

30

o Set different list item markers for unordered lists

o Set an image as the list item marker

List

In HTML, there are two types of lists:

unordered lists - the list items are marked with bullets

ordered lists - the list items are marked with numbers or letters

With CSS, lists can be styled further, and images can be used as the list item marker.

Different List Item Markers

The type of list item marker is specified with the list-style-type property:

Example

ul.a {list-style-type: circle;}

ul.b {list-style-type: square;}

ol.c {list-style-type: upper-roman;}

ol.d {list-style-type: lower-alpha;}

Some of the property values are for unordered lists, and some for ordered lists.

Values for Unordered Lists

Value Description

none No marker

disc Default. The marker is a filled circle

circle The marker is a circle

http://csetube.co.nr/

Page 47: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

square The marker is a square

Values for Ordered Lists

Value Description

armenian The marker is traditional Armenian numbering

decimal The marker is a number

31

decimal-leading-zero The marker is a number padded by initial zeros (01, 02, 03, etc.)

georgian The marker is traditional Georgian numbering (an, ban, gan, etc.)

lower-alpha The marker is lower-alpha (a, b, c, d, e, etc.)

lower-greek The marker is lower-greek (alpha, beta, gamma, etc.)

lower-latin The marker is lower-latin (a, b, c, d, e, etc.)

lower-roman The marker is lower-roman (i, ii, iii, iv, v, etc.)

upper-alpha The marker is upper-alpha (A, B, C, D, E, etc.)

upper-latin The marker is upper-latin (A, B, C, D, E, etc.)

upper-roman The marker is upper-roman (I, II, III, IV, V, etc.)

Note: No versions of Internet Explorer (including IE8) support the property values

"decimalleading-

zero", "lower-greek", "lower-latin", "upper-latin", "armenian", or "georgian" UNLESS a

DOCTYPE is specified!

An Image as The List Item Marker

To specify an image as the list item marker, use the list-style-image property:

Example

ul

{

list-style-image: url('sqpurple.gif');

}

The example above does not display equally in all browsers. IE and Opera will display

the

http://csetube.co.nr/

Page 48: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

image-marker a little bit higher than Firefox, Chrome, and Safari.If you want the image-

marker

to be placed equally in all browsers, a crossbrowser solution is explained below.

Crossbrowser Solution

The following example displays the image-marker equally in all browsers:

Example

ul

{

list-style-type: none;

32

padding: 0px;

margin: 0px;

}

li

{

background-image: url(sqpurple.gif);

background-repeat: no-repeat;

background-position: 0px 5px;

padding-left: 14px;

}

Example explained:

For ul:

o Set the list-style-type to none to remove the list item marker

o Set both padding and margin to 0px (for cross-browser compatibility)

For li:

o Set the URL of the image, and show it only once (no-repeat)

o Position the image where you want it (left 0px and down 5px)

o Position the text in the list with padding-left

http://csetube.co.nr/

Page 49: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

List - Shorthand property

It is also possible to specify all the list properties in one, single property. This is called a

shorthand property.The shorthand property used for lists, is the list-style property:

ul

{

list-style: square url("sqpurple.gif");

}

When using the shorthand property, the order of the values are:

list-style-type

list-style-position (for a description, see the CSS properties table below)

list-style-image

It does not matter if one of the values above are missing, as long as the rest are in the

specified

order.

33

All CSS List Properties

The number in the "CSS" column indicates in which CSS version the property is defined

(CSS1

or CSS2).

Property Description Values CSS

list-style Sets all the properties for a list in one declaration

list-style-type

list-style-position

list-style-image

inherit

1

list-style-image Specifies an image as the list-item marker

URL

http://csetube.co.nr/

Page 50: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

none

inherit

1

list-style-position

Specifies if the list-item markers should appear

inside or outside the content flow

inside

outside

inherit

1

list-style-type Specifies the type of list-item marker

none

disc

circle

square

decimal

decimal-leading-zero

armenian

georgian

lower-alpha

upper-alpha

lower-greek

lower-latin

upper-latin

lower-roman

upper-roman

inherit

1

http://csetube.co.nr/

Page 51: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

34

CSS Tables

The look of an HTML table can be greatly improved with CSS:

Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Berglunds snabbköp Christina Berglund Sweden

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Königlich Essen Philip Cramer Germany

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

North/South Simon Crowther UK

Paris spécialités Marie Bertrand France

The Big Cheese Liz Nixon USA

Vaffeljernet Palle Ibsen Denmark

Table Borders

To specify table borders in CSS, use the border property.The example below specifies a

black

border for table, th, and td elements:Notice that the table in the example above has double

borders. This is because both the table, th, and td elements have separate borders.

Example

table, th, td

{

border: 1px solid black;

}

35

To display a single border for the table, use the border-collapse property.

http://csetube.co.nr/

Page 52: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Collapse Borders

The border-collapse property sets whether the table borders are collapsed into a single

border or

separated:

table

{

border-collapse:collapse;

}

table,th, td

{

border: 1px solid black;

}

Table Width and Height

Width and height of a table is defined by the width and height properties.The example

below sets

the width of the table to 100%, and the height of the th elements to 50px:

table

{

width:100%;

}

th

{

height:50px;

}

CSS CURSORS

Although the cursors will not have the customized look in other browsers it usually

doesn't ruin

http://csetube.co.nr/

Page 53: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

anything. These browsers will simply show the normal arrow-cursor which would be

same case

as if you refrained from cus tomizing cursors at all.So unless the page really doesn't work

without the customized cursor there shouldn't be technical reasons for choosing not

to.However

there might be other reasons for thinking twice before adding custom cursor to your

pages. Many

users are easily confused or irritated when a site breaks the standard user interface.

Adding A Customized Cursor

The syntax for a customized cursor is this:

(Position the mouse over each link to see the effect)

Selector {cursor:value}

36

For example:

<html>

<head>

<style type="text/css">

.xlink {cursor:crosshair}

.hlink{cursor:help}

</style>

</head>

<body>

<b>

<a href="mypage.htm" class="xlink">CROSS LINK</a>

<br>

<a href="mypage.htm" class="hlink">HELP LINK</a>

</b>

</body>

http://csetube.co.nr/

Page 54: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

</html>

2.11 CASE STUDY

Case Study: Revamping an Existing Site

April 27, 2010 32 Comments .

Jacques Soudan, a client and friend I met through DivitoDesign, sent me an email with a

guest post about

a case study on revamping his outdated site. Enjoy reading about his revamping project.

Below is a case-study on how I used the Blueprint CSS Framework and jQuery

JavaScript library to

rebuild an outdated site – somehow you helped me with it, so in return I share my work,

hoping it can be

of future use. Thank you!

The website we are talking about was build back in 2001. As you would understand we

are talking about

a heavily-aged website that had the following ‘problems’ or difficulties:

using some CSS, but mainly tables

the menu is a separate JS file: easy to maintain, but it doesn’t look too good

a few years ago I added the rounded corners (using JavaScript) and the red

backdrop/border, but

that doesn’t look too flashy either

the source is not W3C compliant (outdated code like <br> – instead of the current

<br/&nsbp;>)

37

the footer is embedded in each page (hard to update for about 100 pages)

in general, look & feel is not ‘up to date’

the enquiry form uses a JavaScript file that is no longer supported

in Firefox, the banner is not centered (in IE it is…..) and looks like this (also in a table –

probably

http://csetube.co.nr/

Page 55: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

easy to fix, but never got to it):

For a website in the modern internet world, that is not acceptable. For this reason, I

compiled a list of

features I would like to have on the modern, good looking website.

Site Features we Need

W3C compliant code

CSS and HTML in separated files

browser compatibility

rounded corners & drop shadow

1 central menu file

JavaScript support (instead of using several separate scripts that (might) interfere)

structured design (layout without tables)

Where to Start?

Last year I read this very useful article about building HTML/CSS sites using a template.

This template

has a grid CSS layout and the jQuery framework build in. I had seen those before, but

was not yet using

them in combination with WordPress.

I also found this site for dropshadow & rounded corners. As I wanted to avoid too many

jQuery plugins, I

didn’t use jQuery for the round corners. So far my experience is that jQuery rounded

corners can interfere

with other plugins, needing too much work to fix (and warrant) it.

For this reason, the no-Java-script solution seemed preferable. Provided, it had worked –

it did not – as it

uses several <divs>, it messed up the Blueprint classes, it didn’t display properly

‘underneath’ the header

http://csetube.co.nr/

Page 56: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

images etc. The typical pain when it comes to CSS and different techniques in different

browsers.

So…. dropping Blueprint? Or dropping the very sleek (and easy!) rounded corners?

Dilemma there…..

Until playing around with Blueprint a bit more…. as it comes with grid.png, to display

the columns for

design purposes, which you can switch off when you go live. But then, if you can remove

that backdrop,

why not adding your own???? Using my own image I had created for the initial

technique, but thought

useless now, it worked flawlessly!

38

Here is what I did – in the Blueprint folder, there is a screen.css – just add one line and

comment the gridline

– that’s all!

In your container-DIV, just add the ‘showgrid’-class: (you need that anyway, if you want

to display the

Blueprint-columns):

The grid.png is repeated both horizontally & vertically, but my one large image is not, so

it fits perfectly –

I stretched it to 1600px, as the backdrop is hardly ‘repeatable’: it is a scanned letterhead-

paper with a

unique texture – using only a small slice/strip and repeating that would make it look

unnatural. And I use

a footer-image – including it in php, it neatly fits underneath the length of the actual

content – not the full

background image of 1600px – it ‘stretches’ to the maximum height, but resizes to the

needed height.

http://csetube.co.nr/

Page 57: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

I wanted to use this menu for this website. One problem though: it has no single menu

file (eg. menu.php)

you can add to your website. After building that menu.php file myself, the jQuery menu

worked perfectly.

When I created the header.php and footer.php files and included in the website using

PHP, they are easily

updated in those 100 different pages. Depending on the page of the website, I can now

include different

images via one page. Pretty efficient.

The Template

With all this now in place, this is how the code looks like (this is what I will use as the

‘page-template’

(there is some test copy in, to show in Blueprint columns – all the ‘body-text’ for an

individual page is

placed within the <content-div> (both <span>-classes, in blue) – everything remains in

place, no

fluid/stretched text (in different browsers).

<

<script src="supportfiles/js/jquery.js" type="text/javascript"></script>

<script src="supportfiles/menu/menu.js" type="text/javascript"></script>

<div id="container" class="container showgrid">

39

<div id="header" class="span-24 prepend-top">

<div class="prepend-1 span-22 append-1"></div>

</div>

<!-- end header -->

<div id="CONTENT" class="prepend-1 span-22 append-1 prepend-top">

<div class="span-17">

http://csetube.co.nr/

Page 58: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

<h1>Main content</h1>

Put your main text here (17 columns wide).

</div>

<div class="span-5 last">

<h3>Sidebar</h3>

Some sidebar on the right (5 columns wide).

</div>

</div>

<!-- END CONTENT -->

<div id="footer" class="span-24"></div>

<!-- end footer -->

</div>

<!-- end container -->

Blueprint-grid enabled:

40

And this is how it looks like (pictures not optimized yet):

2.12 . CLIENT SIDE PROGRAMMING:JAVA SCRIPT

Introduction

JavaScript is most commonly used as a client side scripting language. This means that

JavaScript

code is written into an HTML page. When a user requests an HTML page with JavaScript

in it,

the script is sent to the browser and it's up to the browser to do something with

it.JavaScript can

be used in other contexts than a Web browser. Netscape created server-side JavaScript as

a CGIlanguage

that can do roughly the same as Perl or ASP. There is no reason why JavaScript

http://csetube.co.nr/

Page 59: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

couldn’t be used to write real, complex programs. However, this site exclusively deals

with the

41

use of JavaScript in web browsers.I can also recommend Jeremy Keith, DOM Scripting:

Web

Design with JavaScript and the Document Object Model, 1st edition, Friends of Ed,

2005. This,

too, is a book that doesn't delve too deeply into technology, but gives non-programmers

such as

graphic designers/CSS wizards an excellent overview of the most common uses of

JavaScript -

as well as the most common problems.

History and Versions of The JavaScript language

JavaScript is not a programming language in strict sense. Instead, it is a scripting

language

because it uses the browser to do the dirty work. If you command an image to be replaced

by

another one, JavaScript tells the browser to go do it. Because the browser actually does

the work,

you only need to pull some strings by writing some relatively easy lines of code. That’s

what

makes JavaScript an easy language to start with.

But don’t be fooled by some beginner’s luck: JavaScript can be pretty difficult, too. First

of all,

despite its simple appearance it is a full fledged programming language: it is possible to

write

quite complex programs in JavaScript. This is rarely necessary when dealing with web

pages, but

http://csetube.co.nr/

Page 60: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

it is possible. This means that there are some complex programming structures that you’ll

only

understand after protracted studies.

Secondly, and more importantly, there are the browser differences. Though modern web

browsers all support JavaScript, there is no sacred law that says they should support

exactly the

same JavaScript.

JavaScript versions

There have been several formal versions of JavaScript.

1.0: Netscape 2

1.1: Netscape 3 and Explorer 3 (the latter has bad JavaScript support, regardless of its

version)

1.2: Early Version 4 browsers

1.3: Later Version 4 browsers and Version 5 browsers

1.4: Not used in browsers, only on Netscape servers

42

1.5: Current version.

2.0: Currently under development by Brendan Eich and others.

Originally, these version numbers were supposed to give support information. This-and-

that

method would only be supported by browsers understanding JavaScript 1.something .

The higher

the version number, the more nifty features the browser would support.

<script language="javascript1.3" type="text/javascript">

<!--

complex script goes here and is executed

only by browsers that support JavaScript 1.3

// -->

http://csetube.co.nr/

Page 61: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

</script>

<script language="javascript1.0" type="text/javascript">

<!--

simple script goes here and is executed

by all JavaScript browsers

// -->

</script>

Unfortunately Netscape 3 does not recognize the language attribute in a JavaScript

include tag.

So if you do:

<script language="JavaScript1.3" src="somescript.js"></script>

Netscape 3 loads the script, even though it doesn't support JavaScript 1.3, and shows a lot

of error

messages. Too bad.

2.13 INTRODUCTION TO JAVA SCRIPT

What is JavaScript?

JavaScript was designed to add interactivity to HTML pages

JavaScript is a scripting language

A scripting language is a lightweight programming language

A JavaScript consists of lines of executable computer code

A JavaScript is usually embedded directly into HTML pages

JavaScript is an interpreted language (means that scripts execute without preliminary

compilation)

Everyone can use JavaScript without purchasing a license

43

Are Java and JavaScript the Same?

NO!

Java and JavaScript are two completely different languages in both concept and design!

http://csetube.co.nr/

Page 62: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Java (developed by Sun Microsystems) is a powerful and much more complex

programming language - in

the same category as C and C++.

What can a JavaScript Do?

JavaScript gives HTML designers a programming tool - HTML authors are normally not

programmers, but JavaScript is a scripting language with a very simple syntax! Almost

anyone

can put small "snippets" of code into their HTML pages

JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:

document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page

JavaScript can react to events - A JavaScript can be set to execute when something

happens,

like when a page has finished loading or when a user clicks on an HTML element

JavaScript can read and write HTML elements - A JavaScript can read and change the

content

of an HTML element

JavaScript can be used to validate data - A JavaScript can be used to validate form data

before

it is submitted to a server. This saves the server from extra processing

JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect

the

visitor's browser, and - depending on the browser - load another page specifically

designed for

that browser

JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve

information on the visitor's computer

2.14 JAVASCRIPT IN PERSPECTIVE

Examples

http://csetube.co.nr/

Page 63: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Write text with Javascript

The example demonstrates how to use JavaSript to write text on a web page.

44

Write HTML with Javascript

The example demonstrates how to use JavaScript to write HTML tags on a web page.

45

2.15 BASIC SYNTAX

How to Put a JavaScript Into an HTML Page

<html>

<body>

<script type="text/javascript">

document.write("Hello World!");

</script>

</body>

</html>

Hello World!

Example Explained

To insert a JavaScript into an HTML page, we use the <script> tag. Inside the <script>

tag we use the

"type=" attribute to define the scripting language.

So, the <script type="text/javascript"> and </script> tells where the JavaScript starts and

ends:

<html>

<body>

<script type="text/javascript">

...

</script>

</body>

http://csetube.co.nr/

Page 64: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

</html>

The word document.write is a standard JavaScript command for writing output to a page.

By entering the document.write command between the <script> and </script> tags, the

browser will

recognize it as a JavaScript command and execute the code line. In this case the browser

will write Hello

World! to the page:

<html>

<body>

<script type="text/javascript">

document.write("Hello World!");

</script>

</body>

</html>

HTML Comments to Handle Simple Browsers

Browsers that do not support JavaScript will display JavaScript as page content.

46

To prevent them from doing this, and as a part of the JavaScript standard, the HTML

comment tag can be

used to "hide" the JavaScript. Just add an HTML comment tag <!-- before the first

JavaScript statement,

and a --> (end of comment) after the last JavaScript statement.

<html>

<body>

<script type="text/javascript">

<!--

document.write("Hello World!");

//-->

http://csetube.co.nr/

Page 65: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

</script>

</body>

</html>

The two forward slashes at the end of comment line (//) is the JavaScript comment

symbol. This

prevents JavaScript from executing the --> tag.JavaScripts in the body section will be

executed

WHILE the page loads.JavaScripts in the head section will be executed when CALLED.

Examples

Head section

Scripts that contain functions go in the head section of the document. Then we can be

sure that the script

is loaded before the function is called.

47

.

2.16 JAVASCRIPT VARIABLES AND DATATYPES

As with algebra, JavaScript variables are used to hold values or expressions. A variable

can have a short

name, like x, or a more describing name like length. A JavaScript variable can also hold a

text value like

in carname="Volvo".

Rules for JavaScript variable names:

Variable names are case sensitive (y and Y are two different variables)

Variable names must begin with a letter or the underscore character

NOTE: Because JavaScript is case-sensitive, variable names are case-sensitive.

48

Example

http://csetube.co.nr/

Page 66: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

A variable's value can change during the execution of a script. You can refer to a variable

by its name to

display or change its value.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;

var carname;

After the declaration shown above, the variables has no values, but you can assign values

to the variables

while you declare them:

var x=5;

var carname="Volvo";

Assigning Values to JavaScript Variables

You assign values to JavaScript variables with assignment statements:

x=5;

carname="Volvo";

The variable name is on the left side of the = sign, and the value you want to assign to the

variable is on

the right.

After the execution of the statements above, the variable x will hold the value 5, and

carname will hold

the value Volvo.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that has not yet been declared, the variables will

automatically be

declared.These statements:

x=5;

http://csetube.co.nr/

Page 67: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

carname="Volvo";

have the same effect as:

var x=5;

var carname="Volvo";

49

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;

var x;

After the execution of the statements above, the variable x will still have the value of 5.

The value of x is

not reset (or cleared) when you redeclare it.

DataTypes

Numbers - are values that can be processed and calculated. You don't enclose them in

quotation

marks. The numbers can be either positive or negative.

Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses

the

string literally; it doesn't process it. You'll use strings for text you want displayed or

values you

want passed along.

Boolean (true/false) - lets you evaluate whether a condition meets or does not meet

specified

criteria.

Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,

whereas null

is the absence of any value.

Data Types

http://csetube.co.nr/

Page 68: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

TYPE EXAMPLE

Numbers Any number, such as 17, 21, or 54e7

Strings "Greetings!" or "Fun"

Boolean Either true or false

Null A special keyword for exactly that – the null value (that is, nothing)

Integers

In JavaScript, you can express integers in 3 different Bases:

base 10,

base 8 (octal), and

base 16 (hexadecimal).

Base 8 numbers can have digits only up to 7, so a decimal value of 18 would be an octal

value of 22.

50

Similarly, hexadecimal allows digits up to F, where A is equivalent to decimal 10 and F

is 15. So, a

decimal value of 18 would be 12 in hexadecimal notation.

Converting Numbers to Different Bases Table

In order to distinguish between these three bases, JavaScript uses the following notation.

Specifying bases in JavaScript

NUMBER SYSTEM NOTATION

Decimal (base 10) A normal integer without a leading 0 (zero) (ie, 752)

Octal (base 8) An integer with a leading 0 (zero) (ie, 056)

Hexadecimal (base 16) An integer with a leading 0x or 0X (ie, 0x5F or 0XC72)

Floating Point Values

Floating point values can include a fractional component. A floating-point literal includes

a decimal

integer plus either a decimal point and a fraction expressed as another decimal number or

an expression

http://csetube.co.nr/

Page 69: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

indicator and a type suffix

7.2945

-34.2

2e3 means 2 x 103 => 2000

2E-3 means 2 x 10-3 => .002

Floating point literals must, at a minimum, include a decimal integer and either the

decimal point or the

exponent indicator ("e" or "E"). As with integers, floating point values can be positive or

negative.

Strings

Technically, a string literal contains zero or more characters enclosed, as you know, in

single or double

quotes:

"Hello!"

‘245’

"" // This example is called the empty string.

NOTE: the empty string is distinct from the null value in JavaScript.

51

NOTE: Strings are different from other data types in JavaScript. Strings are actually

Objects. This will be

covered later on.

Boolean

A Boolean value is either true or false.

Note: Unlike Java, C and other languages, in JavaScript Boolean values can only be

represented with true

and false. Values of 1 and 0 are not considered Boolean values in JavaScript.

Null Value

http://csetube.co.nr/

Page 70: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

The null value is a special value in JavaScript. The null value represents just that –

Nothing. If you try to

reference a variable that isn’t defined and therefore has no value, the value returned is the

null value.

Likewise, with the prompt() dialog box, if the user selects the Cancel button, a null is

returned.

(example)

NaN (Not a Number)

In addition to these values, some functions return a special value called NaN – which

means that the value

is not a number, parseInt() and parseFloat() are an examples of functions that return NaN

when the

argument passed to them cannot be evaluated to a number.

Creating Values

In order to make working with data types useful, you need ways to store values for later

use. This is

where variables come in.

JavaScript Statements

A JavaScript statements is a command to the browser. The purpose of the command is to

tell the browser

what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people

think this is a good

programming practice, and most often you will see this in JavaScript examples on the

web.

http://csetube.co.nr/

Page 71: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

The semicolon is optional (according to the JavaScript standard), and the browser is

supposed to interpret

the end of the line as the end of the statement. Because of this you will often see

examples without the

semicolon at the end.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.

52

Each statement is executed by the browser in the sequence they are written.

This example will write a header and two paragraphs to a web page:

<script type="text/javascript">

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>

JavaScript Blocks

JavaScript statements can be grouped together in blocks.

Blocks start with a left curly bracket {, and ends with a right curly bracket }.

The purpose of a block is to make the sequence of statements execute together.

This example will write a header and two paragraphs to a web page:

<script type="text/javascript">

{

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

}

</script>

http://csetube.co.nr/

Page 72: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

The example above is not very useful. It just demonstrates the use of a block. Normally a

block is used to

group statements together in a function or in a condition (where a group of statements

should be executed

if a condition is met).

You will learn more about functions and conditions in later chapters.

Where to Put the JavaScript

JavaScripts in a page will be executed immediately while the page loads into the browser.

This is not

always what we want. Sometimes we want to execute a script when a page loads, other

times when a user

triggers an event.

Scripts in the head section: Scripts to be executed when they are called, or when an event

is triggered,

go in the head section. When you place a script in the head section, you will ensure that

the script is

loaded before anyone uses it.

<html>

<head>

<script type="text/javascript">

53

....

</script>

</head>

Scripts in the body section: Scripts to be executed when the page loads go in the body

section. When

you place a script in the body section it generates the content of the page.

<html>

http://csetube.co.nr/

Page 73: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

<head>

</head>

<body>

<script type="text/javascript">

....

</script>

</body>

Scripts in both the body and the head section: You can place an unlimited number of

scripts in your

document, so you can have scripts in both the body and the head section.

<html>

<head>

<script type="text/javascript">

....

</script>

</head>

<body>

<script type="text/javascript">

....

</script>

</body>

Using an External JavaScript

Sometimes you might want to run the same JavaScript on several pages, without having

to write the same

script on every page.

To simplify this, you can write a JavaScript in an external file. Save the external

JavaScript file with a .js

file extension.

http://csetube.co.nr/

Page 74: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Note: The external script cannot contain the <script> tag!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>

<head>

<script src="xxx.js"></script>

54

</head>

<body>

</body>

</html>

2.17 JAVASCRIPT STATEMENTS

A JavaScript statement is a command to the browser. The purpose of the command is to

tell the browser

what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people

think this is a good

programming practice, and most often you will see this in JavaScript examples on the

web.

The semicolon is optional (according to the JavaScript standard), and the browser is

supposed to interpret

the end of the line as the end of the statement. Because of this you will often see

examples without the

semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.

JavaScript Code

JavaScript code (or just JavaScript) is a sequence of JavaScript statements.

http://csetube.co.nr/

Page 75: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Each statement is executed by the browser in the sequence they are written.

This example will write a header and two paragraphs to a web page:

<script type="text/javascript">

document.write("<h1>This is a header</h1>");

document.write("<p>This is a paragraph</p>");

document.write("<p>This is another paragraph</p>");

</script>

2.18 JAVASCRIPT OPERATORS

= is used to assign values.

+ is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

55

The arithmetic operator + is used to add values together.

y=5;

z=2;

x=y+z;

The value of x, after the execution of the statements above is 7.

JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result

+ Addition x=y+2 x=7

- Subtraction x=y-2 x=3

* Multiplication x=y*2 x=10

/ Division x=y/2 x=2.5

% Modulus (division remainder) x=y%2 x=1

++ Increment x=++y x=6

-- Decrement x=--y x=4

http://csetube.co.nr/

Page 76: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result

= x=y x=5

+= x+=y x=x+y x=15

56

-= x-=y x=x-y x=5

*= x*=y x=x*y x=50

/= x/=y x=x/y x=2

%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";

txt2="nice day";

txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "What a verynice

day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";

txt2="nice day";

txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";

txt2="nice day";

txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

http://csetube.co.nr/

Page 77: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

"What a very nice day"

Adding Strings and Numbers

The rule is: If you add a number and a string, the result will be a string!

Example

x=5+5;

document.write(x);

57

x="5"+"5";

document.write(x);

x=5+"5";

document.write(x);

x="5"+5;

document.write(x);

If you add a number and a string, the result will be a string.

Comparison and Logical operators are used to test for true or false.

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference

between variables

or values. Given that x=5, the table below explains the comparison operators:

Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and type) x===5 is true

x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

http://csetube.co.nr/

Page 78: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take

action depending

on the result:

if (age<18) document.write("Too young");

58

You will learn more about the use of conditional statements in the next chapter of this

tutorial.

Logical Operators

Logical operators are used in determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true

Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on

some condition.

Syntax

variablename=(condition)?value1:value2

Example

greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned

the value

"Dear President " else it will be assigned "Dear".

Conditional statements in JavaScript are used to perform different actions based on

different conditions.

Examples

http://csetube.co.nr/

Page 79: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

If statement

How to write an if statement.

59

Conditional Statements

Very often when you write code, you want to perform different actions for different

decisions. You can

use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

if statement - use this statement if you want to execute some code only if a specified

condition is

true

if...else statement - use this statement if you want to execute some code if the condition is

true

and another code if the condition is false

if...else if....else statement - use this statement if you want to select one of many blocks of

code

to be executed

switch statement - use this statement if you want to select one of many blocks of code to

be

executed

If Statement

You should use the if statement if you want to execute some code only if a specified

condition is true.

Syntax

if (condition)

60

{

code to be executed if condition is true

http://csetube.co.nr/

Page 80: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

}

2.19 JAVASCRIPT LITERAL VALUES

Literal values are the ones you type into mathematical or string expressions. For example

23 (an integer),

12.32E23 (a floating point), or 'flopsy the Hamster' (a string).

String literals can be enclosed by either single or double quotes. For example:

'literal string'

"literal string"

'literal string with "double quotes" inside'

There are five special characters you can use in literal strings. These are listed in the table

below.

Reference Meaning

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab

2.10 JAVASCRIPT FUNCTIONS

A function will be executed by an event or by a call to the function.

JavaScript Functions

To keep the browser from executing a script when the page loads, you can put your script

into a

function.A function contains code that will be executed by an event or by a call to the

function.You may

61

call a function from anywhere within a page (or even from other pages if the function is

embedded in an

http://csetube.co.nr/

Page 81: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

external .js file).Functions can be defined both in the <head> and in the <body> section

of a document.

However, to assure that a function is read/loaded by the browser before it is called, it

could be wise to put

functions in the <head> section.

How to Define a Function

Syntax

function functionname(var1,var2,...,varX)

{

some code

}

The parameters var1, var2, etc. are variables or values passed into the function. The { and

the } defines

the start and end of the function.

Note: A function with no parameters must include the parentheses () after the function

name.

Note: Do not forget about the importance of capitals in JavaScript! The word function

must be written in

lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a

function with the

exact same capitals as in the function name.

JavaScript Function Example

<html>

<head>

<script type="text/javascript">

function displaymessage()

{

alert("Hello World!");

http://csetube.co.nr/

Page 82: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

}

</script>

</head>

<body>

<form>

<input type="button" value="Click me!" onclick="displaymessage()" />

</form>

</body>

</html>

If the line: alert("Hello world!!") in the example above had not been put within a

function, it would have

been executed as soon as the page was loaded. Now, the script is not executed before a

user hits the input

button. The function displaymessage() will be executed if the input button is clicked.

62

You will learn more about JavaScript events in the JS Events chapter.

The return Statement

The return statement is used to specify the value that is returned from the function.So,

functions that are

going to return a value must use the return statement.The example below returns the

product of two

numbers (a and b):

Example

<html>

<head>

<script type="text/javascript">

function product(a,b)

{

http://csetube.co.nr/

Page 83: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

return a*b;

}

</script>

</head>

<body>

<script type="text/javascript">

document.write(product(4,3));

</script>

</body>

</html>

Function with a parameter

How to pass a variable to a function, and use the variable in the function.

<html>

<head>

<script type="text/javascript">

function myfunction(txt)

{

alert(txt);

}

</script>

</head>

63

<body>

<form>

<input type="button" onclick="myfunction('Hello')" value="Call function">

</form>

<p>By pressing the button above, a function will be called with "Hello" as a parameter.

The function will

http://csetube.co.nr/

Page 84: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

alert the parameter.</p>

</body>

</html>

Output

By pressing the button above, a function will be called with "Hello" as a parameter. The

function will

alert the parameter

2.21 OBJECTS

JavaScript Objects represent self contained entities consisting of variables (called

properties in object

terminology) and functions (called methods) that can be used to perform tasks and store

complex data.

JavaScript objects fall into three categories: Built-in Objects, Custom Objects and

Document Object

Model (DOM) Objects. Built-in objects are objects that are provided with JavaScript to

make your life as

a JavaScript developer easier. In many of the examples given in this book we have used

the

document.write() mechanism to write text to the current web page. Whether you knew it

or not, you have

been using the write() method of the JavaScript built-in document object when you have

run these scripts.

Document Object Model (DOM) Objects provide the foundation for creating dynamic

web pages. The

DOM provides the ability for a JavaScript script to access, manipulate, and extend the

content of a web

page dynamically (i.e. without having to reload the page). The DOM essentially presents

the web page as

http://csetube.co.nr/

Page 85: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

a tree hierarchy of objects representing the contents and elements of the web page. These

objects, in turn,

contain properties and methods that allow you to access and change parts of the web

page. Custom

objects are objects that you, as a JavaScript developer, create and use.

Creating a Custom JavaScript Object

Creating a custom JavaScript object is quite similar to constructing a function. The syntax

is as follows:

function object(''parameter1, parameter2, parameter3,...'')

{

this.property1 = parameter1;

this.property2 = parameter2;

this.property3 = parameter3;

this.method1 = function1;

this.method2 = function2;

this.method3 = function3;

64

}

In the above outline object refers to the name of the object - this can be any valid (and

hopefully

descriptive) name you choose to use. The parameters define the values that you will pass

into the object

when you instantiate it later.

Creating and Using Object Instances

In the previous section we learned how to create an object definition. It is important to

note that, at this

point, we have only described what the object will do (we have basically created

blueprint of the object),

http://csetube.co.nr/

Page 86: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

we have not actually created an object we can work with (this is known as an object

instance). Object

instances are created using the new keyword and are assigned to an object variable that

will be used to

reference the object. For example, in the following script we will create a new instance of

the car object

with the name myCar:

carObject = new car ("Ford", "Focus", "Red");

We have also passed through parameters to initialize the properties of the object (make,

model and color).

Next we need to understand how to call a method on an object and access an object

property. This is

achieved by using what is called dot notation on the name of the object instance:

To access a property:

objectInstance.propertyName

To call a method of an object:

objectInstance.methodName()

In our example we have a method called displayCar() to display the 3 properties of the

object. Following

the above dot notation syntax we can call this method as follows:

carObject.displayCar()

We can also access a property, for example the color as follows:

document.write ("The make property of myCar is " + myCar.make );

Finally, we can also change one of the properties of an object instance:

myCar.make = "BMW";

Let's now bring all of this together in a complete example within an HTML page:

<html>

65

http://csetube.co.nr/

Page 87: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

<head>

<title>A Simple JavaScript Function Example</title>

<script language="JavaScript" type="text/javascript">

function car (make, model, color)

{

this.make = make;

this.model = model;

this.color = color

this.displayCar = displayCar;

}

function displayCar()

{

document.writeln("Make = " + this.make)

}

</script>

</head>

<script language="JavaScript" type="text/javascript">

myCar = new car ("Ford", "Focus", "Red");

myCar.displayCar();

myCar.make = "BMW";

myCar.displayCar();

</script>

</body>

</html>

Extending Objects

JavaScript object instances are extremely flexible in that they can easily be extended. To

extend an object

http://csetube.co.nr/

Page 88: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

that you have already created use object prototypes. The syntax for prototyping is as

follows:

objectType.prototype.propertyName

Following this syntax we could add a year property to our car class and initialize it to the

year '2001'

using the following:

car.prototype.year = "2001";

When we now create an instance of the object it will contain this new property which can

be read

and manipulated in the same way as all the other properties in this class.

2.22 ARRAYS

The Array object is used to store multiple values in a single variable.

66

Array Object Reference

For a complete reference of all the properties and methods that can be used with the

Array object, go to

our complete Array object reference.The reference contains a brief description and

examples of use for

each property and method!

What is an Array?

An array is a special variable, which can hold more than one value, at a time.

If you have a list of items (a list of car names, for example), storing the cars in single

variables could look

like this:

cars1="Saab";

cars2="Volvo";

cars3="BMW";

http://csetube.co.nr/

Page 89: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

However, what if you want to loop through the cars and find a specific one? And what if

you had not 3

cars, but 300?

The best solution here is to use an array!An array can hold all your variable values under

a single name.

And you can access the values by referring to the array name.Each element in the array

has its own ID so

that it can be easily accessed.

Create an Array

An array can be defined in three ways.

The following code creates an Array object called myCars:

1:

var myCars=new Array(); // regular array (add an optional integer

myCars[0]="Saab"; // argument to control array's size)

myCars[1]="Volvo";

myCars[2]="BMW";

2: var myCars=new Array("Saab","Volvo","BMW"); // condensed array

3: var myCars=["Saab","Volvo","BMW"]; // literal array

Note: If you specify numbers or true/false values inside the array then the variable type

will be Number

or Boolean, instead of String.

67

Access an Array

You can refer to a particular element in an array by referring to the name of the array and

the index

number. The index number starts at 0.

The following code line:

document.write(myCars[0]);

http://csetube.co.nr/

Page 90: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

will result in the following output:

Saab

Modify Values in an Array

To modify a value in an existing array, just add a new value to the array with a specified

index number:

myCars[0]="Opel";

Now, the following code line:

document.write(myCars[0]);

will result in the following output:

`Opel

Join two arrays - concat()

Join three arrays - concat()

Join all elements of an array into a string - join()

Remove the last element of an array - pop()

Add new elements to the end of an array - push()

Reverse the order of the elements in an array - reverse()

Remove the first element of an array - shift()

Select elements from an array - slice()

Sort an array (alphabetically and ascending) - sort()

Sort numbers (numerically and ascending) - sort()

Sort numbers (numerically and descending) - sort()

68

Add an element to position 2 in an array - splice()

Convert an array to a string - toString()

Add new elements to the beginning of an array - unshift()

2.23 BUILT –IN OBJECTS

Java Script String

The String object is used to manipulate a stored piece of text.

http://csetube.co.nr/

Page 91: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Complete String Object Reference

For a complete reference of all the properties and methods that can be used with the

String object, go to

our complete String object reference.

The reference contains a brief description and examples of use for each property and

method!

String object

The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a

string:

var txt="Hello world!";

document.write(txt.length);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a

string to

uppercase letters:

var txt="Hello world!";

document.write(txt.toUpperCase());

The code above will result in the following output:

HELLO WORLD!

JavaScript Date Object

The Date object is used to work with dates and times.

69

Complete Date Object Reference

For a complete reference of all the properties and methods that can be used with the Date

object, go to our

http://csetube.co.nr/

Page 92: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

complete Date object reference.The reference contains a brief description and examples

of use for each

property and method!

Create a Date Object

he Date object is used to work with dates and times. Date objects are created with the

Date() constructor.

There are four ways of instantiating a date:

new Date() // current date and time

new Date(milliseconds) //milliseconds since 1970/01/01

new Date(dateString)

new Date(year, month, day, hours, minutes, seconds, milliseconds)

Most parameters above are optional. Not specifying, causes 0 to be passed in.Once a Date

object is

created, a number of methods allow you to operate on it. Most methods allow you to get

and set the year,

month, day, hour, minute, second, and milliseconds of the object, using either local time

or UTC

(universal, or GMT) time.All dates are calculated in milliseconds from 01 January, 1970

00:00:00

Universal Time (UTC) with a day containing 86,400,000 milliseconds.

Some examples of instantiating a date:

today = new Date()

d1 = new Date("October 13, 1975 11:13:00")

d2 = new Date(79,5,24)

d3 = new Date(79,5,24,11,33,0)

Set Dates

We can easily manipulate the date by using the methods available for the Date object.In

the example

http://csetube.co.nr/

Page 93: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

below we set a Date object to a specific date (14th January 2010):

var myDate=new Date();

myDate.setFullYear(2010,0,14);

And in the following example we set a Date object to be 5 days into the future:

var myDate=new Date();

myDate.setDate(myDate.getDate()+5);

Compare Two Dates

The Date object is also used to compare two dates.

The following example compares today's date with the 14th January 2010

70

var myDate=new Date();

myDate.setFullYear(2010,0,14);

var today = new Date();

if (myDate>today)

{

alert("Today is before 14th January 2010");

}

else

{

alert("Today is after 14th January 2010");

}:

JavaScript Boolean Object

The Boolean object is used to convert a non-Boolean value to a Boolean value (true or

false).

Complete Boolean Object Reference

For a complete reference of all the properties and methods that can be used with the

Boolean object, go to

http://csetube.co.nr/

Page 94: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

our complete Boolean object reference.The reference contains a brief description and

examples of use for

each property and method!

Create a Boolean Object

The Boolean object represents two values: "true" or "false".The following code creates a

Boolean object

called myBoolean:

var myBoolean=new Boolean();

Note: If the Boolean object has no initial value or if it is 0, -0, null, "", false, undefined,

or NaN, the

object is set to false. Otherwise it is true (even with the string "false")!

All the following lines of code create Boolean objects with an initial value of false:

var myBoolean=new Boolean();

var myBoolean=new Boolean(0);

var myBoolean=new Boolean(null);

var myBoolean=new Boolean("");

var myBoolean=new Boolean(false);

var myBoolean=new Boolean(NaN);

And all the following lines of code create Boolean objects with an initial value of true:

71

var myBoolean=new Boolean(1);

var myBoolean=new Boolean(true);

var myBoolean=new Boolean("true");

var myBoolean=new Boolean("false");

var myBoolean=new Boolean("Richard");

JavaScript Math Object

The Math object allows you to perform mathematical tasks.

Complete Math Object Reference

http://csetube.co.nr/

Page 95: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

For a complete reference of all the properties and methods that can be used with the Math

object, go to

our complete Math object reference.The reference contains a brief description and

examples of use for

each property and method!

Math Object

The Math object allows you to perform mathematical tasks.The Math object includes

several

mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=Math.PI;

var sqrt_value=Math.sqrt(16);

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math

object. These are: E,

PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E,

and base-10 log

of E.

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there

are also several

methods available.The following example uses the round() method of the Math object to

round a number

to the nearest integer:

document.write(Math.round(4.7));

The code above will result in the following output: 5

JavaScript RegExp Object

RegExp, is short for regular expression.

http://csetube.co.nr/

Page 96: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

72

Complete RegExp Object Reference

For a complete reference of all the properties and methods that can be used with the

RegExp object, go to

our complete RegExp object reference.The reference contains a brief description and

examples of use for

each property and method!

What is RegExp?

A regular expression is an object that describes a pattern of characters.When you search

in a text, you can

use a pattern to describe what you are searching for.A simple pattern can be one single

character.A more

complicated pattern can consist of more characters, and can be used for parsing, format

checking,

substitution and more.Regular expressions are used to perform powerful pattern-matching

and "searchand-

replace" functions on text.

Syntax

var txt=new RegExp(pattern,modifiers);

or more simply:

var txt=/pattern/modifiers;

pattern specifies the pattern of an expression

modifiers specify if a search should be global, case-sensitive, etc.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.The i modifier is used

to perform caseinsensitive

matching.The g modifier is used to perform a global match (find all matches rather than

stopping after the first match).

http://csetube.co.nr/

Page 97: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Example 1

Do a case-insensitive search for "w3schools" in a string:

var str="Visit W3Schools";

var patt1=/w3schools/i;

he marked text below shows where the expression gets a match:

Visit W3Schools

test()

The test() method searches a string for a specified value, and returns true or false,

depending on the result.

73

exec()

The exec() method searches a string for a specified value, and returns the text of the

found value. If no

match is found, it returns null.

2.24 JAVASCRIPT DEBUGGERS

Firebug

Firebug is a powerful extension for Firefox that has many development and debugging

tools

including JavaScript debugger and profiler.

Venkman JavaScript Debugger

Venkman JavaScript Debugger (for Mozilla based browsers such as Netscape 7.x,

Firefox/Phoenix/Firebird and Mozilla Suite 1.x)

Introduction to Venkman

Using Breakpoints in Venkman

Internet Explorer debugging

Microsoft Script Debugger (for Internet Explorer) The script debugger is from the

Windows 98

and NT era. It has been succeeded by the Developer Toolbar

http://csetube.co.nr/

Page 98: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Internet Explorer Developer Toolbar

Microsofts Visual Web Developer Express is Microsofts free version of the Visual Studio

IDE. It

comes with a JS debugger. For a quick summary of its capabilities see [1]

Internet Explorer 8 has a firebug-like web development tool by default (no add-on) which

can be

accessed by pressing F12. The web development tool also provides the ability to switch

between

the IE8 and IE7 rendering engines.

JTF: Javascript Unit Testing Farm

JTF is a collaborative website that enables you to create test cases that will be tested by

all

browsers. It's the best way to do TDD and to be sure that your code will work well on all

browsers.

jsUnit

jsUnit

Common Mistakes

Carefully read your code for typos.

Be sure that every "(" is closed by a ")" and every "{" is closed by a "}".

Trailing commas in Array and Object declarations will throw an error in Microsoft

Internet

Explorer but not in Gecko-based browsers such as Firefox.

// Object

74

var obj = {

'foo' : 'bar',

'color' : 'red', //trailing comma

};

http://csetube.co.nr/

Page 99: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

// Array

var arr = [

'foo',

'bar', //trailing comma

];

Remember that JavaScript is case sensitive. Look for case related errors.

Don't use Reserved Words as variable names, function names or loop labels.

Escape quotes in strings with a "\" or the JavaScript interpreter will think a new string is

being

started, i.e:

alert('He's eating food'); should be

alert('He\'s eating food'); or alert("He's eating food");

When converting strings to numbers using the parseInt function, remember that "08" and

"09"

(e.g. in datetimes) indicate an octal number, because of the prefix zero. Using parseInt

using a

radix of 10 prevents wrong conversion. var n = parseInt('09',10);

Remember that JavaScript is platform independent, but is not browser independent.

Because

there are no properly enforced standards, there are functions, properties and even objects

that may

be available in one browser, but not available in another, e.g. Mozilla / Gecko Arrays

have an

indexOf() function; Microsoft Internet Explorer does not.

Debugging Methods

Debugging in Javascript doesn't differ very much from debugging in most other

programming languages.

See the article at Computer programming/debugging.

http://csetube.co.nr/

Page 100: Web technology unit II

http:/

/csetu

be.co

.nr/

GKMCETLecture Plan

Subject Name: Web Technology

Subject Code: IT2353

Following Variables as a Script is Running

The most basic way to inspect variables while running is a simple alert() call. However

some

development environments allow you to step through your code, inspecting variables as

you go. These

kind of environments may allow you to change variables while the program is paused.

Browser Bugs

Sometimes the browser is buggy, not your script. This means you must find a

workaround.

http://csetube.co.nr/