Web Notes
Web Notes
Sc CS
WEB PROGRAMMING
Module I
HTML - General Introduction to Internet and WWW; HTML: Structured language, Document
types, Rules of html, Html tags, Head tags, Body tags, Headings , Divisions and Centering,
Quotations, Preformatted text, Lists, Horizontal Rules, Block level elements, Text level
elements, Character entities, Comments, Fonts, Tables: Table tags, Colors, Color names, Color
values ,
Marquee tag.
Module II
Advanced HTML - Linking in html: Anchor tags, Layer tags, Link relationships, URL:Relative,
Absolute, Image, Image maps, Frames: Layouts, Targeting, No frame tag, Floating frames,Audio,
Embed tag, Forms: form tag and its attributes, Get, Post, Form field elements, Form accessibility
enhancements: Access key, Tooltips, Browser-specific form accessibility improvements.
Module III
Javascript - Introduction to Javascript, Variables and data types, Declaring Variables,Operators,
Control Structures, Conditional Statements, Loop Statements, Functions, Objects, Dialog Boxes,
Alert Boxes, Confirm Boxes, Prompt Boxes, Javascript with HTML, Events, Arrays,Predefined
objects, DHTML, Page Redirect, Void Keyword, Page Printing, String Methods, Error
Handling, Validations, Publishing your Site, Cookies
Module IV
CSS & XML: Style sheet Basics, Adding Style to a Document, CSS (Cascading Style Sheet) and
HTML Elements, Selectors, Document Structure and Inheritance
MODULE I
HTML
What is Internet?
The Internet is essentially a global network of computing resources. You can think of the
Internet as a physical collection of routers and circuits as a set of shared resources.
Internet-Based Services
Some of the basic services available to Internet users are −
Email − A fast, easy, and inexpensive way to communicate with other Internet users around the
world.
Telnet − Allows a user to log into a remote computer as though it were a local system.
Eg:Mobile Phone
FTP − Allows a user to transfer virtually every kind of file that can be stored on a computer from one
Internet-connected computer to another.
UseNet news − A distributed bulletin board that offers a combination news and discussion service
on thousands of topics.
What is WWW?
WWW stands for World Wide Web.
World Wide Web is − All the resources and users on the Internet that are using the
Hypertext Transfer Protocol (HTTP).
The World Wide Web is the universe of network-accessible information, an
embodiment of human knowledge.
In simple terms, The World Wide Web is a way of exchanging information between
computers on the Internet, tying them together into a vast collection of interactive
multimedia resources.
What is HTTP?
HTTP stands for Hypertext Transfer Protocol. This is the protocol being used to transfer
hypertext documents that makes the World Wide Web possible.
A standard web address such as http://www.yahoo.com is called a URL and here the
prefix http indicates its protocol
What is URL?
URL stands for Uniform Resource Locator, and is used to specify address of a website in
on the World Wide Web.
A URL is the fundamental network identification for any resource connected to the web
(e.g., hypertext pages, images, and sound files).
Eg: http://www.macas.com
What is Website?
Are collection of various web pages written in HTML language. This is a location on the
web where people can find informations. Similarly, there are millions of websites
available on the web.
Each page available on the website is called a web page and first page of any website is
called home page for that site.
What is ISP?
ISP stands for Internet Service Provider. They are the companies who provide you
service in terms of internet connection to connect to the internet.
You will buy space on a Web Server from any Internet Service Provider. This space will
be used to host your Website.
What is Hyperlink?
A hyperlink or simply a link is a selectable element in an electronic document that
serves as an access point to other electronic resources. Typically, you click the hyperlink
to access the linked resource. Familiar hyperlinks include buttons, icons, image maps,
and clickable text links.
What is DNS?
DNS stands for Domain Name System. When someone types in your domain name,
www.example.com, your browser will ask the Domain Name System to find the IP that
hosts your site. When you register your domain name, your IP address should be put in
a DNS along with your domain name. Without doing it your domain name will not be
functioning properly.
What is HTML?
HTML stands for Hypertext Markup Language, and it is the most widely used language to write
Web Pages.
Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus, the link available on a webpage is called Hypertext.
As its name suggests, HTML is a Markup Language which means you use HTML to
simply "mark-up" a text document with tags that tell a Web browser how to structure
it to display.
<head>
<title>This is document title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes here.....</p>
</body>
</html>
The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the
<html> tag.The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web
browser about what version of HTML the page is written in.The following are types of HTML
documents
This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or
deprecated elements (like font). Framesets are not allowed.
This DTD contains all HTML elements and attributes, INCLUDING presentational and
deprecated elements (like font). Framesets are not allowed.
This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.
This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or
deprecated elements (like font). Framesets are not allowed. The markup must also be written
as well-formed XML.
This DTD contains all HTML elements and attributes, INCLUDING presentational and
deprecated elements (like font). Framesets are not allowed. The markup must also be written
as well-formed XML.
6.XHTML 1.1
This DTD is equal to XHTML 1.0 Strict, but allows you to add modules (for example to provide
Ruby support for East-Asian languages).
HTML Tags
As told earlier, HTML is a markup language and makes use of various tags to format the
content.
HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Formatting elements were designed to display special types of text:
1.<b> - Bold text ,The HTML <b> element defines bold text, without any extra importance.
2.<strong> - Important text, The HTML <strong> element defines strong text, with added
semantic "strong" importance.
3.<i> - Italic text, The HTML <i> element defines italic text, without any extra importance.
4.<em> - Emphasized text, The HTML <em> element defines emphasized text, with added
semantic importance.
5.<sub> - Subscript text ,The HTML <sub> element defines subscripted text.
6.<sup> - Superscript text, The HTML <sup> element defines superscripted text.
Character Entities
Some characters are reserved in HTML, e.g. you cannot use the less than (<) or greater
than (>) signs or angle brackets within your text, because the browser could mistake
them for markup, while some characters are not present on the keyboard like copyright
symbol ©.
To display these special characters, they must be replaced with the character entities.
<audio controls>
<source src="horse.mp3" type="audio/mpeg">
</audio>
The <head> element can include a title for the document, scripts, styles, meta information, and
more.The following elements can go inside the <head> element:
<style>
<base>
<link>
<script>
Example
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
The <h1> to <h6> tags are used to define HTML headings.<h1> defines the most important
heading. <h6> defines the least important heading.
The <body> tag defines the document's body.The <body> element contains all the contents of
an HTML document, such as text, hyperlinks, images, tables, lists, etc.
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
The <div> tag defines a division or a section in an HTML document.The <div> element is often
used as a container for other HTML elements to style them with CSS or to perform certain tasks
with JavaScript.
The <li> tag is used in ordered lists(<ol>), unordered lists (<ul>), and in menu lists (<menu>).
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
The <hr> element is used to represent a thematic break between paragraph-level elements. It is
typically rendered as a horizontal line.
<h1>HTML</h1>
<p>HTML is a language for describing web pages.....</p>
<hr>
<h1>CSS</h1>
<p>CSS defines how to display HTML elements.....</p>
Block-level Elements
A block-level element always starts on a new line and takes up the full width available
(stretches out to the left and right as far as it can).
The <div> element is a block-level element.
Example
<div>Hello</div>
<div>World</div>
Block level elements in HTML:
<address>,<article>,blockquote>,<canvas>,<div>,<footer><form><h1>-
<h6>,<header<ul><video>
Inline Elements
An inline element does not start on a new line and only takes up as much width as necessary.
This is an inline <span> element inside a paragraph.
Example
<span>Hello</span>
<span>World</span>
Inline elements in HTML:
<a><abbr><acronym><b><bdo><big><br><button><cite><code><dfn><em><i><img><input><k
bd><label><map><object><q><samp><script><select><small><span><strong><sub><sup><text
area><time><tt><var>
There are two important tags which we use very frequently to group various other HTML tags
(i) <div> tag and (ii) <span> tag
This is the very important block level tag which plays a big role in grouping various other HTML
tags and applying CSS on group of elements. Even now <div> tag can be used to create
webpage layout where we define different parts (Left, Right, Top etc.) of the page using <div>
tag. This tag does not provide any visual change on the block but this has more meaning when
it is used with CSS.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML div Tag</title>
</head>
<body>
<!-- First group of tags -->
<div style = "color:red">
<h4>This is first group</h4>
<p>Following is a list of vegetables</p>
</div>
</html>
The HTML <span> is an inline element and it can be used to group inline-elements in an HTML
document. This tag also does not provide any visual change on the block but has more meaning
when it is used with CSS.
The difference between the <span> tag and the <div> tag is that the <span> tag is used with
inline elements whereas the <div> tag is used with block-level elements.
Example
<!DOCTYPE html>
<html>
<body>
<p>This is <span style = "color:red">red</span> and this is
<span style = "color:green">green</span></p>
</body>
</html>
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
<!—
Or you can
comment out a large
number of lines.
-->
The <font> tag specifies the font face, font size, and color of text.
Example :
<font size="3" color="red">This is some text!</font>
<font size="2" color="blue">This is some text!</font>
<font face="verdana" color="green">This is some text!</font>
The <marquee> is an HTML tag which was used to create a scrolling text or an image. It was
used to make the text/image scroll horizontally across or vertically down the web page.
The <marquee> element comes in pairs. It means that the tag has opening (<marquee>) and
closing (</marquee>) elements.
Syntax:
MODULE II
Advanced HTML
The HTML <a> element (or anchor element) creates a hyperlink to other web pages,
files, locations within the same page, email addresses, or any other URL.
<a href="url">link text</a>
HTML - Frames
HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document.
HTML-Miscellaneous tags
1.Layer Tag
The HTML <layer> tag is used to position and animate (through scripting) elements in a
page. A layer can be thought of as a separate document that resides on top of the main
one, all existing within one window.
<layer id = "layer1" top = "250" left = "50" width = "200" height = "200" bgcolor = "red">
<p>layer 1</p>
</layer>
<layer id = "layer2" top = "350" left = "150" width = "200" height = "200" bgcolor = "blue">
<p>layer 2</p>
</layer>
2.Imagemap Tag
The <map> tag is used to define a client-side image-map. An image-map is an image with
clickable areas.The required name attribute of the <map> element is associated with the
<img>'s usemap attribute and creates a relationship between the image and the map.
A uniform resource locator (URL) is the address of a resource on the Internet. A URL indicates
the location of a resource as well as the protocol used to access it. There are two types of URL-
Relative and Absolute
An absolute URL contains more information than a relative URL does. Relative URLs are more
convenient because they are shorter and often more portable. However, you can use them only
to reference links on the same server as the page that contains them
The protocol is usually http://, but can also be https://, ftp://, gopher://, or file://.
The domain is the name of the website. For example, the domain name of muslim
association college of arts and science’s web server is www.macas.in
The path includes directory and file information. You must use absolute URLs when
referring to links on different servers.
If the file you want to link to is in a subdirectory of the referring page's directory, you need to
enter only the directory information and the name of the file. So if foobar.html were in the
foobar subdirectory of your www directory, you could refer to it from your home page by using:
HTML Images
In HTML, images are defined with the <img> tag.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
The src attribute specifies the URL (web address) of the image:
<img src="url">
Example
<img src="pic.jpg" alt="my image">
<img src="ipic.jpg" alt="my image" style="width : 500px ; height : 600px;">
Image as a Link
To use an image as a link, put the <img> tag inside the <a> tag:
<a href="page2.html">
<img src="pic.gif" >
</a>
Image Maps
The <map> tag defines an image-map. An image-map is an image with clickable areas.
In the image below, click on the computer, the phone, or the cup of coffee:
<img src="workplace.jpg" >
<map name="workmap">
<area shape="rect" coords="34,44,270,350" alt="Computer" href="computer.htm">
<area shape="rect" coords="290,172,333,250" alt="Phone" href="phone.htm">
<area shape="circle" coords="337,300,44" alt="Coffee" href="coffee.htm">
</map>
The <map> element contains a number of <area> tags, that define the clickable areas in the image-map.
HTML Layouts
Websites often display content in multiple columns (like a magazine or newspaper).
HTML5 offers new semantic elements that define the different parts of a web page:
Value Description
_self Opens the linked document in the same frame as it was clicked
(this is default)
_top Opens the linked document in the full body of the window
<html>
<frameset cols="25%,50%,25%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
<noframes>Sorry, your browser does not handle frames!</noframes>
</frameset>
</html>
Attribute Description
action Specifies a URI/URL of the page that will process the form.
autocomplete Specifies whether the form fields should be automatically completed based on
the user's history (i.e. based on previous forms that the user has completed).
enctype Specifies the content type used to encode the form data set when it's submitted
to the server.
method Specifies the HTTP method to use when the form is submitted.
Possible values:
get (The form data is appended to the URL when submitted. This is the
default value.)
post (The form data is not appended to the URL.)
novalidate Specifies that the form should not be validated during submission.
Possible values:
_blank
_self
_top
_parent
This information is passed using QUERY_STRING header and will be accessible in your
CGI Program through QUERY_STRING environment variable which you can parse and
use in your CGI program.
You can pass information by simply concatenating key and value pairs along with any
URL or you can use HTML <FORM> tags to pass information using GET method.
Example : Alt+m
Tooltip in HTML
Sometimes you want the text to appear only when the user requires it. For example, you might
need to have a short explanation appear below a statement, or a name of a photo to show up
once a user hovers over it. There’s plenty of use cases of hidden text.
.tooltiptext
{
width: 120px;
background-color: red;
color: black;
text-align: center;
border-radius: 6px;
MODULE III
Javascript
What is JavaScript ?
Javascript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages.
It allow client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
Stntax:
<script ...>
JavaScript code
</script>
Example:
<html>
<body>
<script language="javascript" type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>
Client-side JavaScript
Client-side JavaScript is the most common form of javascript language. The script
should be included in HTML document for the code to be interpreted by the browser.
Dynamic web pages can be created by integrating javascript code to HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has
entered a valid e-mail address in a form field.The JavaScript code is executed when the
user submits the form, and only if all the entries are valid, they would be submitted to
the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −
Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
<body>
<script type = "text/javascript">
document.write("Hello World")
</script>
You are not restricted to be maintaining identical code in multiple HTML files. The script tag
provides a mechanism to allow you to store JavaScript in an external file and then include it
into your HTML files.
Here is an example to show how you can include an external JavaScript file in your HTML code
using script tag and its src attribute.
<html>
<head>
<script type = "text/javascript" src = "filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.
For example, you can keep the following content in filename.js file and then you can
use sayHello function in your HTML file after including the filename.js file.
function sayHello()
{
alert("Hello World")
}
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data
type known as object.
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then
refer to the data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
1. Arithmetic Operators
2. Comparison Operators
4. Assignment Operators
1.Arithmetic Operators
JavaScript supports the following arithmetic operators − Assume variable A holds 10 and
variable B holds 20, then −
1 + (Addition)
Adds two operands
Ex: A + B will give 30
2 - (Subtraction)
Subtracts the second operand from the first
Ex: A - B will give -10
3 * (Multiplication)
Multiply both operands
Ex: A * B will give 200
4 / (Division)
Divide the numerator by the denominator
Ex: B / A will give 2
5 % (Modulus)
Outputs the remainder of an integer division
Ex: B % A will give 0
6 ++ (Increment)
Increases an integer value by one
Ex: A++ will give 11
7 -- (Decrement)
Decreases an integer value by one
Ex: A-- will give 9
2.Comparison Operators
JavaScript supports the following comparison operators − Assume variable A holds 10 and
variable B holds 20, then −
1 = = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition
becomes true.
Ex: (A == B) is not true.
2 != (Not Equal)
Checks if the value of two operands are equal or not, if the values are not equal,
3.Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −
2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.
3 ! (Logical NOT)
Reverses the logical state of its operand. If a condition is true, then the Logical
NOT operator will make it false.
Ex: ! (A && B) is false.
4.Bitwise Operators
JavaScript supports the following bitwise operators −Assume variable A holds 2 and variable B
holds 3, then −
2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.
5.Assignment Operators
JavaScript supports the following assignment operators −
1 = (Simple Assignment )
Assigns values from the right side operand to the left side operand
Ex: C = A + B will assign the value of A + B into C
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.
7.Conditional Operator (? :)
The conditional operator first evaluates an expression for a true or false value and then
executes one of the two given statements depending upon the result of the evaluation.
1 ? : (Conditional )
8.typeof Operator
The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number,
string, or boolean value and returns true or false based on the evaluation.
1. if statement
2. if...else statement
1.if statement
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally.
Syntax
The syntax for a basic if statement is as follows −
if (expression)
{
Statement(s) to be executed if expression is true
}
Here a JavaScript expression is evaluated. If the resulting value is true, the given statement(s)
are executed. If the expression is false, then no statement would be not executed. Most of the
times, you will use comparison operators while making decisions.
Example
Try the following example to understand how the if statement works.
2. if...else statement
The 'if...else' statement is the next form of control statement that allows JavaScript to execute
statements in a more controlled way.
Syntax
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}
Here JavaScript expression is evaluated. If the resulting value is true, the given statement(s) in
the ‘if’ block, are executed. If the expression is false, then the given statement(s) in the else
block are executed.
Example
Try the following code to learn how to implement an if-else statement in JavaScript.
Syntax
The syntax of an if-else-if statement is as follows −
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Statement(s) to be executed if no expression is true
}
There is nothing special about this code. It is just a series of if statements, where each if is a
part of the else clause of the previous statement. Statement(s) are executed based on the true
condition, if none of the conditions is true, then the else block is executed.
Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.
Output
Maths Book
Set the variable to different value and then try...
You can use multiple if...else…if statements, as in the previous chapter, to perform a multiway
branch. However, this is not always the best solution, especially when all of the branches
depend on the value of a single variable.
Starting with JavaScript 1.2, you can use a switch statement which handles exactly this
situation, and it does so more efficiently than repeated if...else ifstatements.
4.switch Statement
The following flow chart explains a switch-case statement works.
The objective of a switch statement is to give an expression to evaluate and several different
statements to execute based on the value of the expression. The interpreter checks
each case against the value of the expression until a match is found. If nothing matches,
a default condition will be used.
switch (expression)
{
case condition 1:
statement(s)
break;
case condition 2:
statement(s)
break;
...
case condition n:
statement(s)
break;
default: statement(s)
}
The break statements indicate the end of a particular case. If they were omitted, the
interpreter would continue executing each statement in each of the following cases.
Example
Try the following example to implement switch-case statement.
case 'B':
document.write("Pretty good<br />");
break;
case 'C':
document.write("Passed<br />");
break;
case 'D':
case 'F':
document.write("Failed<br />");
break;
default:
document.write("Unknown grade<br />")
}
document.write("Exiting switch block");
</script>
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Looping in JavaScript
While writing a program, you may encounter a situation where you need to perform an action
over and over again. In such situations, you would need to write loop statements to reduce the
number of lines.
JavaScript supports all the necessary loops to ease down the pressure of programming.
Syntax
The syntax of while loop in JavaScript is as follows −
while (expression)
{
Statement(s) to be executed if expression is true
}
Example
Try the following example to implement while loop.
<script type="text/javascript">
var i = 0;
while (i < 10)
{
document.write( i + "<br />");
count++;
}
</script>
Output
1
2
3
4
5
6
7
8
9
10
Do
{
Statement(s) to be executed;
}
while (expression);
Example
<script type="text/javascript">
var i= 0;
do
{
document.write( i + "<br />");
i++;
}
while (i < 5);
</script>
Output
1
2
3
4
5
3. The 'for' loop
It is the most compact form of looping. It includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not. If the condition is
true, then the code given inside the loop will be executed, otherwise the control will
come out of the loop.
The iteration statement where you can increase or decrease your counter.
You can put all the three parts in a single line separated by semicolons.
Syntax
The syntax of for loop is JavaScript is as follows −
Example
Try the following example to learn how a for loop works in JavaScript.
Output
1
2
3
4
Example
The following example illustrates the use of a break statement with a while loop. Notice how
the loop breaks out early once x reaches 5 and reaches to document.write (..) statement just
below to the closing curly brace −
<script type="text/javascript">
var x = 1;
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
</script>
Output
1
2
3
4
5
Example
This example illustrates the use of a continue statement with a while loop. Notice how
the continue statement is used to skip printing when the index held in variable x reaches 5 −
<script type="text/javascript">
var x = 1;
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skip rest of the loop body
}
document.write( x + "<br />");
}
</script>
Output
Entering the loop
2
3
4
6
7
8
9
10
FUNTIONS IN JAVASCRIPT
A function is a group of programming code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes. Functions allow a programmer to divide a big
program into a number of small and manageable functions.
Like any other advanced programming language, JavaScript also supports all the
features necessary to write modular code using functions.
JavaScript allows us to write our own functions as well. This section explains how to
write your own functions in JavaScript.
Function Definition
Before we use a function, we need to define it. 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
The basic syntax is shown here.
<script type="text/javascript">
function functionname(parameter-list)
{
statements
}
</script>
Example
Try the following example. It defines a function called sayHello that takes no parameters −
<script type="text/javascript">
function sayHello()
{
alert("Hello there");
}
</script>
Calling a Function
To invoke a function somewhere later in the script, you would simply need to write the name
of that function as shown in the following code.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
What is an Event ?
JavaScript's interaction with HTML is handled through events that occur when the user
or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too
is an event. Other examples include events like pressing any key, closing a window,
resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause
buttons to close windows, messages to be displayed to users, data to be validated, and
virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.
Here we will see a few examples to understand a relation between Event and JavaScript −
Example
Try the following example.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
2.onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the webserver. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.
<html>
<head>
<script type="text/javascript">
function validation()
{
</head>
<body>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function over()
{
document.write ("Mouse Over");
}
function out()
{
document.write ("Mouse Out");
}
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
</body>
</html>
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one
button "OK" to select and proceed.
Example
<html>
<head>
<script type="text/javascript">
<!--
function Warn()
{
alert ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>
</body>
</html>
Output
If the user clicks on the OK button, the window method confirm() will return true. If the user
clicks on the Cancel button, then confirm() returns false. You can use a confirmation dialog box
as follows.
Example
<html>
<head>
<script type="text/javascript">
function getConfirmation()
{
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
Output
The prompt dialog box is very useful when you want to pop-up a text box to get user input.
Thus, it enables you to interact with the user. The user needs to fill in the field and then click
OK.
This dialog box is displayed using a method called prompt() which takes two parameters: (i) a
label which you want to display in the text box and (ii) a default string to display in the text
box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window
method prompt() will return the entered value from the text box. If the user clicks the Cancel
button, the window method prompt()returns null.
Example
The following example shows how to use a prompt dialog box −
<html>
<head>
<script type="text/javascript">
<!--
function getValue()
{
var retVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Output
Syntax
Use the following syntax to create an Array object −
You will use ordinal numbers to access and to set values inside an array as follows.
Array Properties
Here is a list of the properties of the Array object along with their description.
1 constructor
2 index
The property represents the zero-based index of the match in the string
3 input
4 length
In the following sections, we will have a few examples to illustrate the usage of Array
properties.
Objects in JavaScript
Objects are composed of attributes. If an attribute contains a function, it is considered to be a
method of the object, otherwise the attribute is considered a property.
Object Properties
Object properties can be any of the three primitive data types, or any of the abstract data
types, such as another object. Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible variables that are used throughout the
page.
objectName.objectProperty = propertyValue;
For example − The following code gets the document title using the "title"property of
the document object.
Object Methods
Methods are the functions that let the object do something or let something be done to it.
There is a small difference between a function and a method – at a function is a standalone
unit of statements and a method is attached to an object and can be referenced by
the this keyword.
For example − Following is a simple example to show how to use the write() method of
document object to write any content on the document.
document.write("This is test");
The Date object is a datatype built into the JavaScript language. Date objects are created with
the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods
simply allow you to get and set the year, month, day, hour, minute, second, and millisecond
fields of the object, using either local time or UTC (universal, or GMT) time.
You can use any of the following syntaxes to create a Date object using Date() constructor.
new Date( )
new Date(milliseconds)
new Date(datestring)
Void Keyword
The void operator is used to evaluate a JavaScript expression without returning a value. void is an
important keyword in JavaScript which can be used as a unary operator that appears before its single
operand, which may be of any type.
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate
an expression for its side-effects without the browser displaying the value of the evaluated expression.
Syntax
void (expression)
void expression
Example
<head>
<script type = "text/javascript">
void func()
javascript:void func()
void(func())
javascript:void(func())
</script>
</head>
<html>
<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>
Example
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Output : sln=26
2. indexOf() method returns the index of (the position of) the first occurrence of a specified
text in a string:
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
JavaScript counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third ...
Pos returnd the value 8
3.Searching for a String in a String :The search() method searches a string for a specified
value and returns the position of the match:
Example
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate");
4.Extracting String Parts :There are 3 methods for extracting a part of a string:
1. slice(start, end)
2. substring(start, end)
3. substr(start, length)
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
var str = "Apple, Banana, Kiwi";
var res = str.slice(7, 13);
The result of res will be:
Banana
The replace() method replaces a specified value with another value in a string:
Example
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "MACAS");
Output : Please visit MACAS
Example
var text1 = "Hello World!"; // String
var text2 = text1.toUpperCase(); // text2 is text1 converted to upper
A string is converted to lower case with toLowerCase():
Example
var text1 = "Hello World!"; // String
var text2 = text1.toLowerCase(); // text2 is text1 converted to lower
Example
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2);
The concat() method can be used instead of the plus operator. These two lines do the same:
8.String.trim()
String.trim() removes whitespace from both sides of a string.
Example
var str = " Hello World! ";
alert(str.trim());
str.charAt(0); // returns H
The charCodeAt() Method
The charCodeAt() method returns the unicode of the character at a specified index in a string:
Example
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
here are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c)
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript
Runtime Errors
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors are not the
result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic
that drives your script and you do not get the result you expected.
Exception Handling
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
try
// Code to run
catch ( e )
finally
// an exception occurring
</script>
JavaScript Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.
Most often, the purpose of data validation is to ensure correct user input. Server side
validation is performed by a web server, after input has been sent to the server. Client side
validation is performed by a web browser, before input is sent to a web server.
If a form field is empty, this function alerts a message, and returns false, to prevent the form
from being submitted:
JavaScript Example
function validateForm()
var x = document.forms["myForm"]["fname"].value;
if (x == "")
return false;
Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<script>
function validate()
if (isNaN(num))
return false;
3.Format Validation
Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.
function validateform()
var password=document.myform.password.value;
if(password.length<6)
return false;
var pwd=document.myform.password.value;
var pwd1=document.myform.password.value;
if(pwd!=pwd1)
return false;
5.Email validation
There are many criteria that need to be follow to validate the email id such as:
<script>
function validateemail()
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
return false;
</script>
HTTP COOKIES
Cookies are key/value pairs used by websites to store state informations on the browser. Say
you have a website (example.com), when the browser requests a webpage the website can
send cookies to store informations on the browser.
HTTP protocol is a stateless protocol. But for a commercial website it is required to maintain
session information among different pages. For example one user registration ends after
transactions which spans through many pages. But how to maintain user's session information
across all the web pages?
In many situations, using cookies is the most efficient method of remembering and tracking
information of visitor for better experience or site statistics.
How It Works
Your server sends some data to the visitor's browser in the form of a cookie. The browser may
accept the cookie. If it does, it is stored as a plain text record on the visitor's hard
drive(memory). Now, when the visitor arrives at another page on your site, the cookie is
available for retrieval. Once retrieved, your server knows/remembers what was stored.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.
Path − The path to the directory or web page that set the cookie.
Secure − If this field contains the word "secure" then the cookie may only be retrieved with a
secure server. If this field is blank, no such restriction exists.
SET COOKIES
document.cookie = 'foo=bar'
If you don’t set anything else, the cookie will expire when the browser is closed. To prevent so,
add an expiration date, expressed in the UTC format (Mon, 26 Mar 2018 17:04:05 UTC)
The path parameter specifies a document location for the cookie, so it’s assigned to a specific
path, and sent to the server only if the path matches the current document location, or a
parent:
DELETE A COOKIE
To delete a cookie, unset its value and pass a date in the past:
MODULE IV
Cascading Style Sheet
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out,
what background images or colors are used, layout designs,variations in display for different
devices and screen sizes as well as a variety of other effects.
Advantages of CSS
CSS saves time − You can write CSS once and then reuse same sheet in multiple HTML pages. You
can define a style for each HTML element and apply it to as many Web pages as you want.
Pages load faster − If you are using CSS, you do not need to write HTML tag attributes every time.
Just write one CSS rule of a tag and apply it to all the occurrences of that tag. So less code means
faster download times.
Easy maintenance − To make a global change, simply change the style, and all elements in all the
web pages will be updated automatically.
Superior styles to HTML − CSS has a much wider array of attributes than HTML, so you can give a far
better look to your HTML page in comparison to HTML attributes.
CSS - Syntax
A CSS comprises of style rules that are interpreted by the browser and then applied to the
corresponding elements in your document. A style rule is made of three parts −
Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1>
or <table> etc.
Property − A property is a type of attribute of HTML tag. Put simply, all the HTML attributes are
converted into CSS properties. They could be color, border etc.
Value − Values are assigned to properties. For example, color property can have value
either red or #F1F1F1 etc.
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
<html>
<head>
</head>
<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>
An external style sheet is a separate text file with .css extension. You define all the Style rules
within this text file and then you can include this file in any HTML document using <link>
element.
XML tags identify the data and are used to store and organize the data, rather than specifying
how to display it like HTML tags, which are used to display the data.
There are three important characteristics of XML that make it useful in a variety of systems
and solutions −
XML is extensible − XML allows you to create your own self-descriptive tags, or language, that suits
your application.
XML carries the data, does not present it − XML allows you to store the data irrespective of how it
will be presented.
XML is a public standard − XML was developed by an organization called the World Wide Web
Consortium (W3C) and is available as an open standard.
XML Usage
A short list of XML usage says it all −
XML can work behind the scene to simplify the creation of HTML documents for large web sites.
XML can be used to exchange the information between organizations and systems.
XML can easily be merged with style sheets to create almost any desired output.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>
An XML document is a basic unit of XML information composed of elements and other
markup in an orderly package.
An XML document can contains wide variety of data. For example, database of
numbers, numbers representing molecular structure or a mathematical equation.
XML Document Example
A simple document is shown in the following example −