Professional Documents
Culture Documents
Unit – I
HTML : HTML tags, Lists, Tables, Images, forms, Frames.
Cascading style sheets.
JavaScript : Introduction to Java script, Objects in Java Script, Dynamic HTML
with Java Script.
HTML stands for Hyper Text Markup Language. It is the primary language used to encode
documents containing hyperlinks. HTML is a markup language for describing web documents
(web pages). HTML is defined with the use of the Standard Generalized Markup Language
(SGML), which is an ISO standard notation for describing text-formatting languages.HTML file is
text file containing small markup tags. Its markup tags tell the web browser how to display the
page.
HTML History
Since the early days of the web, there have been many versions of HTML:
Initially work on HTML was started in 1989 by Tim Berners Lee.
In 1995, HTML 2.0 was published by IETF (Internet Engineering Task Force). HTML 2.0 is
the first standard HTML specification.
In 1997, HTML 3.2 was published by W3C (World Wide Web Consortium).
In 1997, HTML 4.0 was published by W3C. It provides three variations: strict, transitional
and frameset.
In 1999, HTML 4.01 was published by W3C.
A markup language is a set of markup tags. HTML documents are described by HTML tags. The
fundamental syntactic units of HTML are called tags. Each HTML tag describes different
document content. HTML tags are keywords (tag names) surrounded by angular brackets:
The first tag in a pair is the opening tag; the second tag is the closing tag. The end tag is written
like the opening tag, but with a slash before the tag name. Whatever appears between a tag and
its closing tag is the content of the tag. Not all tags can have content. The opening tag and its
closing tag together specify a container for the content they enclose. The container and its content
together are called an element.
HTML elements can be nested (elements can contain elements). All HTML documents consist of
nested HTML elements. This example contains 4 HTML elements:
Eg:
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Attributes : HTML elements can have attributes. Attributes specify alternative meanings of a tag.
They can be written between an opening tag‟s name and its right angle bracket. They are
specified in keyword form, which means that the attribute‟s name is followed by an equals sign
and the attribute‟s value i.e., attributes come in name/value pairs like: name="value". Attribute
names, like tag names, are written in lowercase letters. Attribute values must be delimited by
double quotes.
Comments : to increase the readability of the program. In HTML comments are enclosed between
<!—- and -->
<!—-This is a comment -->
A body section can contain comments, block and inline elements, character entities, tables,
forms, hyperlinks, images, lists etc.
Block elements are displayed like blocks of text. Browsers display block elements as text
followed with a line break and some padding automatically. Some of the block elements are
paragraphs, headings, preformatted text, lists etc. Inline elements have no automatic line break or
padding like block elements. Examples for inline elements are bold, big text, small text, strong
text etc.
Heading elements can carry the following attributes : align, class, id, style, title, dir, lang
Attribute Value Description
align left, center, Indicates the alignment of the heading.
right
The paragraph tags, <p> and </p> provides the most basic block formatting for web page text.
Their use is straightforward. Place the opening tag (<p>) at the start of the paragraph and the
ending tag (</p>) at the end of the paragraph. The user agent (browser) will render the text in
Example :
<p>This is first paragraph</p>
<p>This is second paragraph</p>
Paragraph <p> element can carry the following attributes : align, class, id, style, title, dir, lang
For example
<p>Web Technologies <br /> HTML</p>
Displays
Web Technologies
HTML
Presentational Elements
Bold Text : Anything that appears within <b>...</b> element, is displayed in bold.
Italic Text : Anything that appears within <i>...</i> element is displayed in italicized.
Underlined Text : Anything that appears within <u>...</u> element, is displayed with underline.
Strike Text : Anything that appears within <strike>...</strike> element is displayed with
strikethrough, which is a thin line through the text.
Superscript Text : The content of a <sup>...</sup> element is written in superscript; the font size
used is the same size as the characters surrounding it but is displayed half a character's height
above the other characters.
Subscript Text : The content of a <sub>...</sub> element is written in subscript; the font size
used is the same as the characters surrounding it, but is displayed half a character's height
beneath the other characters.
Larger Text: The content of the <big>...</big> element is displayed one font size larger than the
rest of the text surrounding it.
Smaller Text : The content of the <small>...</small> element is displayed one font size smaller
than the rest of the text surrounding it.
Horizontal Lines : <hr /> element
Example :
<!DOCTYPE html>
<html>
<head>
<title>Text Formatting</title>
</head>
<body>
<p><b>Bold Text </b></p>
<p><i>Italicized Text </i></p>
<p><i>Underlined Text </i></p>
<p><strike>Strikethrough</strike>text </p>
<p>Superscript text : (a+b)<sup>2</sup> </p>
<p>Subscript text : log<sub>2</sub> </p>
<p>Larger text : <big>Big</big> </p>
<p>Smaller text : <small>Small</small> </p>
</body>
</html>
Grouping Content
The <div> and <span> elements allow you to group together several elements to create sections
or subsections of a page.
For example, you might want to put all of the footnotes on a page within a <div> element to
indicate that all of the elements within that <div> element relate to the footnotes. You might then
attach a style to this <div> element so that they appear using a special set of style rules.
The <span> element, on the other hand, can be used to group inline elements only. So, if you
have a part of a sentence or paragraph which you want to group together, you could use the
<span> element as follows.
<!DOCTYPE html>
<html>
<head>
<title>Div Tag Example</title>
</head>
<body>
<div id="menu" align="middle" >
<a href="/index.htm">HOME</a> |
<a href="/about/contact_us.htm">CONTACT</a>
<a href="/about/index.htm">ABOUT</a>
</div>
<p>This is the example of <span
style="color:green">span tag</span> and the <span
style="color:red">div tag</span> alongwith CSS</p>
</body>
</html>
Lists
Lists are used to display list of items in the webpage. It is possible to create three types of lists in
HTML
Unordered lists - they are like lists of bullet points
Ordered lists - uses sequence of numbers or letters instead of bullets
Definition lists - allows to specify a term and its definition
Unordered Lists:
<ul> element is used to create unordered lists. Each bullet point or the text is enclosed in between
<li>…</li> tags, stands for list item. A list item can contain any html element like images, links
etc.
Attributes of <ol> tag are
Attribute Value Description
Compact Compact Specifies that the list should render smaller than normal
Type Disc | square Specifies the kind of marker to use in the list
| circle
Example:
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered Lists:
These are used to display the items, for those the order is mandatory. The list items can be
prefixed with numbers (1, 2, 3…), upper case letters(A, B, C…), lower case letters(a, b, c….),
roman numeral both upper and lower case(I, II, III…i, ii,iii..).
An ordered list is contained inside <ol> tag.
Each list item is enclosed between <li>…</li>
Apart from compact and type attributes, it has an additional start attribute.
Definition Lists
The definition lists are special kind of lists for providing terms followed by a short text definition
or description for them. These lists are contained inside <dl> element.
<dl> element contains alternating <dt> and <dd> elements.
<dt> element contains the term of definition.
<dd> element contains the description for the definition.
Following example describes different kinds of lists using definition lists.
<dl>
<dt>Unordered List</dt>
<dd>A list of bullet points</dd>
<dt>Ordered List</dt>
<dd>A numbered list</dd>
<dt>Definition List</dt>
<dd>A list of terms and definitions</dd>
</dl>
Nested Lists
It is possible to nest one list inside another list. For example a numbered list with separate points
corresponding to one of the list items.
<ol type=”I”>
<li>Item One</li>
<li>Item Two</li>
<li>Item Three</li>
<li>Item Four
<ol type=”i”>
<li>Item 4.1 </li>
<li>Item 4.2 </li>
<li>Item 4.3 </li>
</ol>
</li>
<li>Item Five</li>
</ol>
Links
A webpage can contain various links that take you directly to other pages and even
specific parts of a given page. These links are known as hyperlinks. Hyperlinks allow visitors to
navigate between Web sites by clicking on words, phrases, and images.
Internal navigation
The id attribute can be used to create bookmarks inside HTML documents. Anchor tag can be
used to provide internal navigation by using id attribute. The target location within the web
document is marked by using id attribute.
Eg. <h1 id=”top”> main heading</h1>
The anchor tag which is used to reach that particular heading is
<a href=”#top”>heading</a>
For internal navigation using anchor tag, href is specified as elements id preceded by „#‟ sign.
Example :
<html>
<head><title>Internal Navigation</title> </head>
<body>
<ul>
<li><a href="#one">HTML</a></li>
<li><a href="#two">CSS</a></li>
<li><a href="#three">JavaScript</a></li>
</ul>
<table> Element
The <table> element is the containing element for all tables.
An HTML table consists of the <table> element and one or
more <tr>, <th>, and <td> elements. The table tag carry all
universal attributes like align, bgcolor, border, cellpadding,
cellspacing, dir, frame, rules, summary, width
Attribute Value Description
Border 0 – default Specifies the width of the table border in pixels.
Any numeral
Cellpadding Amount of space Used to create a gap between the edges of a cell and its
or padding in contents
pixels Eg: cellpadding=”5”
Cellspacing Amount of space Used to create space between the borders of adjacent cells.
in pixels Eg: cellspacing = “6”
Summary Text Specifies a summary of the content of a table
Width Pixels | % Specifies the width of a table
<tr> element
The <tr> element is used to contain each row in a
table. Anything appearing within a <tr> element
should appear on the same row. It can carry align,
bgcolor, valign attributes.
<caption> attribute
<caption> element is used to add caption to a table. <caption> element is used after the opening
<table> tag and before the first row or header
Example :
<html>
<body>
<table align="center" border="1">
<caption>Courses - Intake</caption>
<tr>
<th rowspan="2">Course</th>
<th colspan="2">Details</th>
</tr>
<tr>
<th>Branch name</th>
<th>Intake</th>
</tr>
<tr>
<td rowspan=3>B.Tech.</td>
<td>CSE</td><td>180</td>
</tr>
<tr>
<td>ECE</td>
<td>180</td>
</tr>
<tr>
<td>EEE</td>
<td>120</td>
</tr>
</table>
</body>
</html>
<img> tag carries the following attributes : src, alt, align, border, height, width, hspace, vspace, ismap,
usemap name.
Forms
A form is used to collect information from the visitor of a site. It is a mechanism supported by
HTML which allows data to be sent from client to the server for processing. A form is created by
combining form controls, such as text boxes, checkboxes, select boxes and radio buttons and so
on. When a user fills in a form, the data is sent to the server in name/value pairs. The name
corresponds to the name of the form control, and the value is what the user has entered
<form> element
A form can be created in a web document by using <form> tags. Any form live inside an element
called <form>. Form controls are placed in between <form> ….</form>. A <form> element can
also contain other HTML markups such as paragraphs, headings, and so on. A <form> element
must not contain another <form> element.
Every <form> element should carry at least two attributes: action method
This element may also carry enctype, accept, accept-charset, onsubmit, onreset attributes.
Form Controls
Different types of form controls that are used to collect data from a visitor are
Text input controls Select boxes
Buttons File select boxes
Checkboxes and radio buttons Hidden controls
<input> element
The <input> tag specifies an input field where the user can enter data. <input> elements are used
within a <form> element to declare input controls that allow users to input data. An input field
can vary in many ways, depending on the type attribute.
Text Inputs
These are used to take text input and are created using <input> and <textarea> elements.
Buttons
Buttons are most commonly used to submit a form, although they are sometimes used to
clear or reset form and even to trigger client-side scripts. To create buttons using <input> element
, type attribute can take the following values.
Submit, which creates a button that automatically submits a form
Reset, which creates a button that automatically resets form controls to their initial values.
Button, which creates a button that is used to trigger a client-side script when the user
clicks that button. Examples are shown below.
Checkboxes
As with light switches, checkboxes can be either on or off. When they are checked they are
on and the user can simply toggle between on and off positions by clicking the checkbox.
Checkboxes can appear individually, with each having its own name, or they can appear as a
group of checkboxes that share a control name and allow users to select several values for the
same property.
A checkbox is created using the <input> element whose type attribute has a value of checkbox.
Following is an example of some checkboxes that use the same control name.
<input type=”checkbox” name=”skills” value=”html” /> HTML
<input type=”checkbox” name=”skills” value=”css” /> CSS
<input type=”checkbox” name=”skills” value=”js” /> Java Script
Radio Buttons
Radio buttons are similar to checkboxes in that they can be either on or off, but the key difference
is - When you have a group of radio buttons that share the same name, only one of them can be
selected. Once one radio button has been selected, if the user clicks another option, the new
option is selected and the old one deselected. The <input> element is used to create radio buttons
with type attribute set to “radio”
<input type=”radio” name=”skills” value=”html” /> HTML
<input type=”radio” name=”skills” value=”css” /> CSS
<input type=” radio” name=”skills” value=”js” /> Java Script
Frames
Frames divide a browser window into several separate pieces or panes, each pane containing a
separate HTML page. One of the key advantages offered by frames is, loading and reloading of
single panes without having to reload the entire contents of the browser window. A collection of
frames in the browser window is known as a frameset.
The window is divided into frames much as tables are organized: into rows and columns.
<frame> element
The <frame> element indicates what goes in each frame of the frameset. The <frame> element is
always an empty element, and therefore should not have any content, although each <frame>
element should always carry one attribute, src, to indicate the page that should represent that
frame.
The element can carry any of the universal attributes, and the following attributes: frameborder
marginwidth marginheight noresize scrolling longdesc src name
Attribute Value Description
Frameborde Number Specifies whether or not to display a border around a frame
r • „0‟ means no border
• Any numerical value other than „0‟ shows the border
Border Number Specifies the width of the border in pixels / percentages
Noresize Noresize Specifies that a frame is not resizable.
scrolling Yes, no, auto Specifies whether or not to display scrollbars in a frame
Example:
<frameset cols="25%,*,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
Cascading Style Sheets (CSS) allows you to define how you want your html document to
look. They allow webpage designers to improve and change the appearance of their webpages
very efficiently. This concerns features such as typeface, background, link colors, margins, and
placement of objects on a page. CSS Level 1 (or version 1) became a World Wide Web
Consortium (W3C) recommendation in 1996. The CSS Level 2 specification or version came into
effect in 1998.
In the early days of HTML, one could define the various parts of a document (such as
headings, body text, bold, etc.), but it was up to the browser to interpret what that was supposed
There were certain display features, such as margins, that were not possible to create
unless you created strange workarounds with the available tags, such as tables. These
workarounds resulted in problems such as longer download times and very messy coding. Then,
whenever there was a change to a website, such as your boss saying, “let‟s change our website
color scheme”, this meant editing many, many pages. The W3C decided to tackle these problems
by developing the CSS standard and urging all browser companies to comply with the standards.
Advantages
1. Style sheets make managing the look of multiple web pages MUCH easier by separating
CONTENT from DISPLAY information.
2. They make web pages faster to download, very important when you are trying to reach
people with older computers.
3. The W3C is slowly phasing out old ways of coding HTML in its standards, for example the
use of the <font> tag. This translates into: professional standards are moving toward style
sheets.
4. Complexity of webpages increases significantly by writing presentation information
within webpages and changing the presentation on demand required considerable
overhead – style sheets solve these problems easily by separating document presentation
from document content written in markup languages.
5. A style sheet can be applied to different documents.
6. CSS provides many more style attributes for defining the look and feel of a webpage than
plain HTML.
Benefits
More powerful formatting than using presentation tags
Your pages load faster, because browsers cache the .css files
Increased accessibility, because rules can be defined according given media
Pages are easier to maintain and update
Style Rules:
The display instructions are called “style rules” in CSS. Style rules are simply a way of telling
anyone‟s browser how to make your web page look.
Example :
h1 {color: red;} - means “I want my <h1> headers‟ text color to be red.”
You can have more than one declaration, or rule, for each selector. Just separate them with semi-
colons. It is to recommend to put each new rule on a new line, for easy reading. Put the ending
curly bracket after the last one.
h1 {color: red;
background: yellow;}
The above declaration means “I want all my <h1> headers‟ text color to be red and set in a
background that is yellow.” This is the pattern that you will use to compose ALL of your style
rules:
Selectors are basic building blocks of style rules. – They determine elements on which
rules are to be applied. Selector having common declarations are grouped into a comma
separated list.
Universal selector applies its style to all elements in the document, it is denoted by ( * )
Eg: * { color : red; }
Makes all elements in the document red.
Descendent selector, allow us to determine the elements depending upon their hierarchical
relationship.
Eg: p b { color:red; }
<b>Hello </b> <p> <b> World! </b> </p>
Output is : Hello World!
Inline Styles
Style information is incorporated directly into the HTML opening tags and apply only to
the content of that tag.
This is least flexible styling method.
Styles for an HTML element is specified using style attribute.
General form of style attribute is
Style = “ property-1:value1; property-2:value2;………; property-n:valuen;”
<html>
<body>
</body>
</html>
Example: myStyle.css
<html> body {
<head> background-color: #d0e4fe;
<link rel="stylesheet" type="text/css" color: #006600;
href="mystyle.css" /> }
</head>
<body> h1 {
color: orange;
<h1>My First CSS Example</h1> text-align: center;
<p>This is a paragraph.</p> }
<h2>This heading has no style defined for it
</h2> p{
font-family: "Times New Roman";
</body> font-size: 20px;
</html> color: #330099;
}
If more number of styles are specified in a HTML document, following order is followed to
resolve the conflicting styles. Top style is having highest importance and last one is having least
importantce.
Inline Style
Internal Styles
External Styles
Browsers default style
Class selectors
To allow different occurrences of the same tage to use different style specifications class selectors
are used. CSS class allows you to style items within the same HTML element differently. A class
selector begins with a ( . ) period . A style class name is attached to a tag name with a period.
e.g: <style>
p.normal { property-value list}
p.warning { property-value list}
</style>
The class is specified in the document body with the class attribute of the affected tag
Generic class
Generic classes provide the convenience of applying class of style specifications to the content of
more than one kind of tag. This is defined without a tag name in its name.
Eg: < style>
.sale { property-value list }
</style>
Usage in the body of the document
<h3 class=”sale”> . . . . . . . .</h3>
<p class=”sale”>. . . . . . . . .</p>
Id selector
An id selector allows the application of a style to one specific element.
CSS IDs are similar to the classes, except that once a specific ID has been declared, it
cannot be used again within the same HTML file.
IDs are used to style the layout elements of a page that are required only once.
Classes are used to style text such that they may be declared multiple times.
CSS Properties
Font
When you style font, the most typical thing to change is the size. For HTML nowadays,
font size is not measured in “points” but in “ems.” An em is the size of the capital letter “M” in
the default font and font size which was set by the user‟s browser, which means that it could be
anything! However, this flexibility is very important. If you remember from the Accessibility
lecture, different people need different sized fonts: a visually-impaired person might have their
computer set for large size font, whereas someone else might like very small size font. You the
designer shouldn‟t force an exact size on the user, but should build in flexibility to your design to
accommodate users‟ needs. So, using an em as a unit of measurement provides web designers
with some amount of control and precision in their fonts and widths, while allowing for
flexibility on the viewer‟s part.
Font size, therefore, is relative: 1em is the size of a capital M at 100%, if you want it
smaller, you could put 0.8em which would make your font 80% of the size of the default M; if
you want it larger you can make it 1.2em which would be 120% the size of a default M, and so on.
Colors
There are sixteen pre-defined colors in HTML: aqua, black, blue, fuchsia, gray, green, lime,
maroon, navy, olive, purple, red, silver, teal, white, and yellow. That means, you can just type the
word “blue” into your code, and the browser will give you the default color for blue. If you want
more variety or nuance, there are also 216 “web safe colors” that all browsers should be able to
read accurately. You can use these colors by using the “HEX” color code system (a combination
of A-F and 0-9 to six places). The HEX system works on the RGB principle: each color is a
combination of Red Green and Blue, and the code is divided in three parts, with the first two
spaces representing Red, the second two Green, and the third two Blue. F is the highest, and 0 is
the lowest; so here are some basic patterns:
#000000 = black (total absence of color, all zeros) #FFFFFF = white (presence of all colors, all Fs)
#FF0000 = red (the red section at full level) #00FF00 = green (the green section at full level)
#FF8800 = a shade of orange (red plus green) What do you think the code would be for blue?
margin-left: 10px; width: 100px; height: 252px; padding: 5px 5px 5px 5px;
For example
border: #FF00FF 15px dotted; (for all borders)
border-color: #FF00F; (for all borders color is red)
border-left: #FF00FF 15px dotted; (only left border)
border-bottom-style: dashed; (only bottom border style is dashed)
JavaScript
Overview
JavaScript is a programming language for use in HTML pages. Invented in
1995 at Netscape Corporation. JavaScript is not Java, or even related to Java. The original
name for JavaScript was “LiveScript”. The name was changed when Java became
popular. Statements in JavaScript resemble statements in Java, because both languages
borrowed heavily from the C language. JavaScript is a complete, full-featured, complex
language.
4. Java is loaded from compiled byte code whereas JavaScript is loaded as human
readable source code.
5. Java supports block based scoping whereas JavaScript supports function based
scoping.
6. Objects in Java are class based whereas objects in JavaScript are prototype based.
The script can be kept in a separate file so you have two files, one HTML and the
other JavaScript, and the HTML file uses the SRC attribute in the SCRIPT
element to specify the name of the JavaScript file. An external .js file lets you use
the same JavaScript on multiple HTML pages. The external .js file cannot itself
contain a <script> tag.
<head>
<script src="myJavaScriptFile.js"></script>
</head>
JavaScript can be put in an HTML form object, such as a button. This JavaScript
will be executed when the form object is used.
JavaScript code is executed during the page loading or when the browser fires an
event
o All statements are executed at page loading
o Some statements just define functions that can be called later
Function calls or code can be attached as "event handlers" via tag attributes
o Executed when the event is fired by the browser
Benefits of JavaScript
JavaScript has a number of big benefits to make webpage dynamic.
It is widely supported in webbrowsers.
Gives easy access to the document objects and can manipulate most of them.
It can give interesting animations (without long downloading times)
No need of special plug-in to use scripts.
JavaScript is relatively secure (it neither reads from local drive not writes to it)
Provides HTML designers a programming tool.
Can react to events.
JavaScript allows interactivity such as:
o Implementing form validation
o React to user actions, e.g. handle keys
o Changing an image on moving mouse over it
o Sections of a page appearing and disappearing
o Content loading and changing dynamically
o Performing complex calculations
o Custom HTML controls, e.g. scrollable table
o Implementing AJAX functionality
Fundamentals
Variables : variables are the dataitems that can be manipulated as the program runs. A
variable is a named value that are used in programs. Before you use a variable, you
must declare it, using the reserved word var. For example if you want to use a variable
called price, you would include
var price;
in your script. After that you could give a value to that variable by saying
price=2.50;
There is no need to delete or set it to null, if we have finished with a variable. Browser
will automatically delete when different webpage is loaded.
Rules for constructing variable names:
You should choose variable names that make sense to you, the programmer.
Choose names like incomeTax or rateOfPay or priceOfFish, not x or i
Variable names are case-sensitive.
Variable names must begin with a letter, digit or an underscore.
Do not use reserverd words
Scope : The scope of a variable is the region of your program in which it is defined.
o Global variables : has local scope which means it can be accessed
anywhere in a JavaScript code.
o Local variables : will be visible only within a function where it is defined
Function parameters are always local to that function
Reserved Words
Reserved words have some special meaning.
They cannot be used as variables, function names, methods, loop labels etc.
break else new var
case finally return void
catch for switch while
continue function this with
default if throw
delete in try
do instanceof typeof
Datatypes
Javascript provides primitive datatypes, composite datatypes and special datatypes
Primitive datatypes
o String : Consists of a sequence of zero or more unicode characters
Eg: var s = “Hello word”;
o Number : to hold an integer or a real number
Eg: var x=123; y=45.9;
o Boolean : can have only two values , either true or false.
JavaScript is a loosely typed language, the declaration for a string variable, a number
and a boolean is same. But is differentiates a string variable, a number and a boolean
from the literal value assigned to it and the context of its use.
Operators
An operator is a symbol used to perform an operation. Generally work on variables or
on constants. JavaScript supports
o Arithmetic Operators
o Comparison Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Miscellaneous Operators
Arithmetic Operators if yes then condition becomes true.
Operator Description
Logical Operators
+ Adds two operands
Operator Description
- Subtracts second operand from the first
&& Called Logical AND operator. If both the
* Multiply both operands operands are non zero then then condition
becomes true.
/ Divide numerator by denumerator
|| Called Logical OR Operator. If any of the
% Modulus Operator and remainder of after two operands are non zero then then
an integer division condition becomes true.
++ Increment operator, increases integer
value by one ! Called Logical NOT Operator. Use to
reverses the logical state of its operand. If a
-- Decrement operator, decreases integer condition is true then Logical NOT
value by one operator will make false.
> Checks if the value of left operand is << Called Bitwise Shift Left Operator.
greater than the value of right operand, if
yes then condition becomes true. >> Called Bitwise Shift Right with Sign
Operator.
< Checks if the value of left operand is less
than the value of right operand, if yes then >>> Called Bitwise Shift Right with Zero
condition becomes true. Operator.
Conditional Operators :
evaluates an expression for a true or false value and then execute one of the two given
statements depending upon the result of the evaluation. The conditional operator has this
syntax
Condition ? Value if true : value if false
typeof Operator :
is a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the data type of the operand.
Displaying Content
JavaScript can "display" data in different ways:
Writing into an alert box, using window.alert().
Writing into the HTML output using document.write().
Writing into an HTML element, using innerHTML.
Conditional Statements
if statement - use this statement to execute some code only if a specified condition is true
Syntax:
if (condition) {
block of code to be executed if the condition is true
}
Example :
if (time < 20) {
greeting = "Good day";
}
if...else statement - use this statement to execute some code if the condition is true and another
code if the condition is false.
Syntax:
if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}
Example
if...else if....else statement - use this statement to select one of many blocks of code to be executed
Syntax:
if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}
Example
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
switch statement - use this statement to select one of many blocks of code to be executed. Switch
selects between number of choices depending upon the value of the expression. Choices are
identified by case statements, each has a label which equals one of potential values of expression.
Optional default may be used, if none of the cases matches the expression. Every case includes one
or more statements and is terminated by a break.
Syntax: Example
switch(expression) { switch (new Date().getDay()) {
case n: case 0:
code block day = "Sunday";
break;
break; case 1:
case n: day = "Monday";
code block break;
break; case 2:
default: day = "Tuesday";
default code block break;
} case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
}
While loop - loops through a block of code while a specified condition is true.
Syntax:
while (condition) {
code block to be executed
}
do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and
then it will repeat the loop as long as the specified condition is true.
Syntax:
do {
code block to be executed
} while (condition);
for - loops through a block of code a specified number of times. It is the most compact form of
looping and includes the following three important parts:
o The loop initialization where we initialize our counter to a starting value. The initialization
statement is executed before the loop begins.
o The test statement which will test if the given condition is true or not. If condition is true
then code given inside the loop will be executed otherwise loop will come out.
o The iteration statement where you can increase or decrease your counter.
Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true }
Break and continue
The break statement can be used to jump out of a loop. It breaks the loop and continues
executing the code after the loop (if any):
for (i = 0; i < 10; i++) {
if (i == 3) break;
text += "The number is " + i + "<br>";
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
for (i = 0; i <= 10; i++) {
if (i == 3) continue;
text += "The number is " + i + "<br>";
}
Functions
A function is a group of reusable code which can be called anywhere in your program. The most
common way to define a function in JavaScript is by using the function keyword, followed by a
unique function name, a list of parameters (that might be empty), and a statement block
surrounded by curly braces.
Syntax:
<script type="text/javascript">
function functionname(parameter-list) {
statements
}
</script>
Example : Calculate the product of two numbers, and return the result:
function myFunction(a, b) {
return a * b;
}
Function calling
var x = myFunction(4, 3);
function name can be any combination of digits, letters, and underscore but cannot contain a
space.
Parameter Passing
When a function receives a value as a parameter, that value is given a name and can be accessed
using that name by a function.
Ex: following function takes 3 parameters name, age, shoesize.
function about_you(name, age, shoe_size)
{
document.write(“<p>Your name is “ + name);
document.write(“<p>You are“ + age + “years old”);
document.write(“<p>Your shoe size is “ + shoe_size);
}
To call this function when the page is loaded, write the body tag like this
<body onLoad=”about_you(“sai”,7,8)”>
Or simply call this like below.
about_you(“sai”,7,8)
complete javascript on to pass variables to a function, and use these variable values in the
function.
<html>
<head>
<script type="text/javascript">
function myfunction(txt) {
alert(txt)
}
</script>
</head>
<body>
<form>
<input type="button" onclick="myfunction('Good Morning')" value="In the Morning">
<input type="button" onclick="myfunction('Good Evening')" value="In the Evening">
</form>
<p>By pressing a button, a function will be called. The function will alert using the argument
passed to it.
</body>
</html>
Example
<html>
<head>
<script type="text/javascript">
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i ++)
sum += parseInt(arguments[i]);
return sum;
}
alert(sum(1, 2, 4));
</script>
</head>
</html>
Returning values
To return values from a function return statement is used.
var reset = my_func(32);
function my_func(number)
{
var answer = Math.sin(number);
retrun answer;
}
Scoping Rules
Scoping determine how a variable can be accessed. In JS, variables can be either local/global.
Global scoping means that a variable is available to all parts of the program. They are declared
outside of any function.
Local Scoping means variables are declared inside a function. They can only be used by that
function.
Pop-up boxes
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
prompt( ) : The prompt() method displays a dialog box that prompts the visitor for input. A
prompt box is often used if you want the user to input a value before entering a page. The
prompt() method returns the input value if the user clicks "OK". If the user clicks "cancel" the
method returns null.
Syntax: window.prompt("sometext","defaultText");
Example: var person = prompt("Enter the price", "10.00");
confirm( ) : A confirm box is often used if you want the user to verify or accept something. When
a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user
clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax : window.confirm("sometext");
Example:
var r = confirm("Press a button");
if (r == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
Objects in JavaScript
JavaScript is not a true Object-oriented language. It tries to be an Object-oriented language.
It diverges from traditional OO in its treatment of user defined objects. An object is a collection of
related methods and properties. Properties represent features and methods represent actions
performed upon those objects.
An object can be created easily by using object literal. An object literal is a comma
separated list of property-value pairs written within a pair of curly braces. The name and its
value are separated by “:”. Once an object is created its properties can be accessed using dot ( . )
operator. Javascript allows us to access the property of an object using array notation also like
objectname[„propertyname‟].
A class in javascript is defined by a function, which acts as constructor definition for class.
Objects are created with the help of this constructor function and the new operator. Class
definition for class point is given below.
function Point( ){
}
To create an object
Origin = new Point( );
Built-in Objects
It is possible to use some of the built-in JavaScript objects directly in your code
– document.write(“The value of PI is “ + Math.PI);
Other objects require you to instantiate a new object
– var studentList = new Array()
Garbage collection : When a new object is instantiated, some memory is reserved. JavaScript
Automatically cleans up the memory, when a program no longer needs a variable or object
Arrays
An array is an ordered set of data elements which can be accessed through a single
variable name. data elements in an array can be accessed sequentially by reading from beginning,
or by their index. The index is the position of the element in the array. Array is a special type of
object in JavaScript. Its main function is to hold data until the script requires it.
to used the array method, specify the name of the array, which we want to operate on, followed
by a dot, then the name of the function and specify the parameters if any
arrayname.function(parameter1, parameter2, ……)
The real strength of JavaScript arrays are the built-in array properties and methods:
Properties and methods
length - The length property of an array returns the length of an array
Example:
<script>
var alpha = ["a", "b", "c"];
var numeric = [1, 2, 3];
var an =alpha.concat(numeric);
document.write("after concatenation : " + an);
an.pop();
an.push(4);
document.write("<br \>after push and pop : " + an);
an.reverse();
document.write("<br \>after reversing : " + an);
an.sort();
document.write("<br \>after reversing : " + an);
</script>
Output :
after concatenation : a,b,c,1,2,3
after push and pop : a,b,c,1,2,4
after reversing : 4,2,1,c,b,a
after reversing : 1,2,4,a,b,c
String Object
Javascript automatically converts between string primitives and String objects. Creating
a String object:
var s1 = new String(“…string …. “);
The string parameter is series of characters that has been properly encoded.
Example :
<script type="text/javascript">
var s1 = new String("Hello World!");
document.write("character at 3 : " + s1.charAt(3));
document.write("<br \>character code at 3 : " + s1.charCodeAt(3));
document.write("<br \>length : " + s1.length);
document.write("<br \>index of World : " + s1.indexOf("World"));
document.write("<br \>last index of character l is : " + s1.lastIndexOf("l"));
document.write("<br \>uppercase : " + s1.toUpperCase());
document.write("<br \>lowercase : " + s1.toLowerCase());
</script>
Output :
character at 3 : l
character code at 3 : 108
length : 12
index of World : 6
last index of character l is : 9
uppercase : HELLO WORLD!
lowercase : hello world!
Math Properties:
Property Description
E Euler's constant and the base of natural logarithms, approximately 2.718.
LN2 Natural logarithm of 2, approximately 0.693.
LN10 Natural logarithm of 10, approximately 2.302.
LOG2E Base 2 logarithm of E, approximately 1.442.
LOG10E Base 10 logarithm of E, approximately 0.434.
PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.
SQRT1_2 Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
SQRT2 Square root of 2, approximately 1.414.
Math Methods
Method Description
abs() Returns the absolute value of a number.
acos() Returns the arccosine (in radians) of a number.
asin() Returns the arcsine (in radians) of a number.
atan() Returns the arctangent (in radians) of a number.
ceil() Returns the smallest integer greater than or equal to a number.
cos() Returns the cosine of a number.
exp() Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.
floor() Returns the largest integer less than or equal to a number.
log() Returns the natural logarithm (base E) of a number.
max() Returns the largest of zero or more numbers.
min() Returns the smallest of zero or more numbers.
pow() Returns base to the exponent power, that is, base exponent.
random() Returns a pseudo-random number between 0 and 1.
round() Returns the value of a number rounded to the nearest integer.
sin() Returns the sine of a number.
sqrt() Returns the square root of a number.
tan() Returns the tangent of a number.
Date Object
The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
different variant of Date() constructor:
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Example :
<script type="text/javascript">
var dt = new Date();
document.write("Date and Time : " + dt );
document.write("<br\> getFullYear() : " + dt.getFullYear() );
document.write("<br\> getDay() : " + dt.getDay() );
document.write("<br\> getHours() : " + dt.getHours() );
</script>
Output :
Date and Time : Thu Feb 05 2015 10:32:35 GMT+0530 (India Standard Time)
getFullYear() : 2015
getDay() : 4
getHours() : 10
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
The DOM API is used to access, traverse and manipulate HTML and XML documents. A basic
and simplified outline of typical DOM hierarchy is shown below.
properties
closed, defaultStatus , name, document, history, location, frames, navigator, screen, screenLeft,
screenTop.
methods of window object
Method Description
alert(msg) Displays a dialog box with a specified message and an OK button
blur( ) Removes focus from the window
clearInterval( ) Cancels a timeout that was set using the setInterval( ) method
close( ) Closes the window
confirm(msg) Displays a dialog box with the specified message and OK and cancel
buttons
focus() Gives focus to this window
moveBy(dx, dy) Moves this window by the specified number of pixels.
moveTo(x,y) Moves the top left corner of the window to the specified screen
coordinates.
print( ) Prints the contents of the window or frame
open( ) Opens a new browser window
prompt(msg) Displays a dialog box with a message and an input field.
stop( ) Stops the current download
Location object
This object encapsulates the current URL that is displayed in the visitor‟s browser. It has several
useful properties and methos
Property Description
Href The entire URL
Hostname URL hostname
Host Hostname and port section
Port Port section
Protocol URL protocol name including “:”
Method Description
Reload( ) Current URL is reloaded
Replace(URL) Loads the specified URL by replacing the current one
History Object
This object stores information about URLs already visited from the browser‟s window.
Property Description
current Current document URL
length Number of entries of the history object
next Next URL in the history object
previous Previous URL in the history object.
Method Description
back( ) Loads previous URL in the history list
forward( ) Loads the next URL in the history list.
Document object
JavaScript document object has many properties that are considerably useful to web application
developers. Some properties of document object are
alinkcolor, anchors, applets, bgcolor, fgcolor, cookie, domain, forms, images, lastModified, linkcolor, links,
title, URL, vlinkcolor.
Method Description
document.write() Writes HTML expressions or JavaScript code to a document
document.writeln()
document.getElementById() Returns the element that has the ID attribute with the specified
value
document.getElementsByClassName() Returns a NodeList containing all elements with the specified
class name
document.getElementsByName() Returns a NodeList containing all elements with a specified name
document.getElementsByTagName() Returns a NodeList containing all elements with the specified tag
name
The process of linking an event handler with an event is known as registration. There are two
ways to register an event handler in DOM 0 event model. First way is by assigning the event
handler script to an event tag attribute as shown below:
<head>
<title>JavaScript Demo</title>
<script type="text/javascript">
function calcSum() {
value1 = parseInt(document.myForm.textBox1.value);
value2 = parseInt(document.myForm.textBox2.value);
sum = value1 + value2;
document.myForm.textBoxSum.value = sum;
}
</script>
</head>
<body>
<form name="myForm">
First Number : <input type="text" name="textBox1" /> <br/> <br/>
Second Number : <input type="text" name="textBox2" /> <br/> <br/>
<input type="button" value="Process" onClick="calcSum()" />
<input type="text" name="textBoxSum" readonly="readonly"/>
</form>
</body>
</html>
Form validation
It would be nice to validate data that is entered into your forms at the client. Validation is simply
the process of ensuring that some data might be correct for a particular application. Two of the
form aspects can be manipulated using Javascript.
1. The data entered onto the form can be checked at submission.
2. One can actually build forms using JS.
The elements of form are held in an array. The events which are used to trigger validation
routines are onclick, onsubmit and onreset. By performing validations at client side, load on the
server reduces there by causes saving in network bandwidth and provides quick response.
Following example illustrates form validation.
<html>
<head>
<script type="text/javascript">
function validate() {
var uname = document.getElementById('uname').value;
var upwd = document.getElementById('upwd').value;
if (uname==""){
alert("Enter User name");
return false;
}
Data validation is the process of ensuring that users submit only the set of characters which you
require. It is not the process of ensuring that the data is anyway accurate.
DHTML
HTML is based on thinking of a web page like a printed page: a document that is rendered
once and that is static once rendered. The idea behind Dynamic HTML (DHTML), however, is to
make every element of a page interactively controllable, before, during, and after the page is
rendered. This means you can make things move, appear and disappear, overlap, change styles,
and interact with the user to your heart‟s content. Through DHTML, users get a more engaging
and interactive web experience without constant calls to a web server or the overhead of loading
new pages, plug-ins, or large applets.
DHTML is not a language itself, but is a combination of:
HTML 4.0 (or XHTML 1.0)
JavaScript – the Web‟s standard scripting language
Cascading Style Sheets (CSS) – styles dictated outside a document‟s content
Document Object Model (DOM) – a means of accessing a document‟s individual
elements
The web page here uses simple DHTML to change the style of links to be red and underlined
when the mouse is rolled over them