WEB PROGRAMMING I Course Notes
WEB PROGRAMMING I Course Notes
WEB PROGRAMMING I
Course notes
Proposed by Mr. TAFOPA Igor
Internet services allows us to access huge amount of information such as text, graphics, sound
and software over the internet. Following diagram shows the four different categories of Internet
Services.
a. Communication Services
There are various Communication Services available that offer exchange of information with
individuals or groups. The following table introduces these services:
1 Electronic mail
Used to send electronic message over the internet.
2 Telnet
Used to log on to a remote computer that is attached to internet.
5 Mailing Lists
Used to organize group of internet users to share common information through e-mail.
There exist several Information retrieval services offering easy access to information present on
the internet. The following table introduces these services:
2 Archie
It has updated database of public FTP sites and their content. It helps to search a file by
its name.
3 Gopher
Used to search, retrieve, and display documents on remote sites.
c. Web Services
Web services allow exchange of information between applications on the web. Using web
services, applications can easily interact with each other.
WWW is also known as W3. It offers a way to access documents spread over the several servers
over the internet. These documents may contain texts, graphics, audio, video, hyperlinks. The
hyperlinks allow the users to navigate between the documents.
This is how to break down the information using the following URL as an example:
www.supremecourt.gov/opinions/12pdf/11-697_d1o2.pdf
2.1 OVERVIEW
HTML stands for Hyper Text Markup Language. It is a formatting language used to define the
appearance and contents of a web page. It allows us to organize text, graphics, audio, and video
on a web page.
Key Points:
The word markup refers to the symbols that are used to define structure of the text. The
markup symbols tells the browser how to display the text and are often called tags.
The word Language refers to the syntax that is similar to any other language.
HTML Versions
Version Year
XHTML 2000
HTML5 2012
A Tag is a command that tells the web browser how to display the text, audio, graphics or video
on a web page.
Key Points:
They start with a less than (<) character and end with a greater than (>) character.
Most of the tags usually occur in pair: the start tag and the closing tag.
The start tag is simply the tag name is enclosed in angle bracket whereas the closing tag is
specified including a forward slash (/).
Some tags are the empty i.e. they don’t have the closing tag.
The starting and closing tag name must be the same. For example <b> hello </i> is invalid
as both are different.
If you don’t specify the angle brackets (<>) for a tag, the browser will treat the tag name
as a simple text.
Basic tags
The following table shows the Basic HTML tags that define the basic web page:
Tag Description
<! DOCTYPE…> This tag defines the document type and HTML version
<head> </head> Specifies the descriptive information about the web documents.
Heading Tags
Any document starts with a heading. You can use different sizes for your headings. HTML also
has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>.
While displaying any heading, browser adds one line before and one line after that heading.
Example
<!DOCTYPE html>
<html>
<head>
<title>Heading Example</title>
</head>
<body>
</html>
Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of text
should go in between an opening <p> and a closing </p> tag as shown below in the example:
Example
<!DOCTYPE html>
<html>
<head>
<title>Paragraph Example</title>
</head>
<body>
</body>
</html>
<br />
So here <p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are
some HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br />
elements. These are known as void elements.
HTML documents consists of a tree of these elements and they specify how HTML documents
should be built, and what kind of content should be placed in what part of an HTML document.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
An attribute is used to define the characteristics of an HTML element and is placed inside the
element's opening tag. All attributes are made up of two parts: a name and a value:
• The name is the property you want to set. For example, the paragraph <p> element in the
example carries an attribute whose name is align, which you can use to indicate the
alignment of paragraph on the page.
• The value is what you want the value of the property to be set and always put within
quotations. The below example shows three possible values of align attribute: left, center
and right.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Core Attributes
The four core attributes that can be used on the majority of HTML elements (although not all)
are:
• Id
• Title
• Class
• Style
The Id Attribute
The id attribute of an HTML tag can be used to uniquely identify any element within an HTML
page. There are two primary reasons that you might want to use an id attribute on an element:
• If you have two elements of the same name within a Web page (or style sheet), you can
use the id attribute to distinguish between elements that have the same name.
We will discuss style sheet in separate tutorial. For now, let's use the id attribute to distinguish
between two paragraph elements as shown below.
Example
The behavior of this attribute will depend upon the element that carries it, although it is often
displayed as a tooltip when cursor comes over the element or while the element is loading.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
The value of the attribute may also be a space-separated list of class names. For example:
class="className1"
<html>
<head>
</head>
<body>
</body>
</html>
Some text...
Generic Attributes
Here's a table of some other attributes that are readily usable with many of the HTML tags.
Attribute Options Function
We will see related examples as we will proceed to study other HTML tags. For a complete list of
HTML Tags and related attributes please check reference to HTML Tags List.
If you use a word processor, you must be familiar with the ability to make text bold, italicized, or
underlined; these are just three of the ten options available to indicate how text can appear in
HTML and XHTML.
Bold Text
Anything that appears within <b>...</b> element, is displayed in bold as shown below −
Example
<!DOCTYPE html>
<html>
<head>
<title>Bold Text Example</title>
</head>
<body>
<p>The following word uses a <b>bold</b> typeface.</p>
</body>
</html>
Italic Text
Anything that appears within <i>...</i> element is displayed in italicized as shown below −
Example
<!DOCTYPE html>
<html>
<head>
<title>Italic Text Example</title>
</head>
<body>
<p>The following word uses an <i>italicized</i> typeface.</p>
</body>
</html>
Underlined Text
Anything that appears within <u>...</u> element, is displayed with underline as shown below −
<head>
<title>Underlined Text Example</title>
</head>
<body>
<p>The following word uses an <u>underlined</u> typeface.</p>
</body>
</html>
Strike Text
Anything that appears within <strike>...</strike> element is displayed with strikethrough, which
is a thin line through the text as shown below −
Example
<!DOCTYPE html>
<html>
<head>
<title>Strike Text Example</title>
</head>
<body>
<p>The following word uses a <strike>strikethrough</strike> typeface.</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.
Example
<!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>
</html>
Content Articles
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.
Example
<!DOCTYPE html>
<html>
<head>
<title>Span Tag Example</title>
</head>
<body>
<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>
This is the example of span tag and the div tag alongwith CSS
These tags are commonly used with CSS to allow you to attach a style to a section of a page.
Insert Image
You can insert any image in your web page by using <img> tag. Following is the simple syntax
to use this tag.
The <img> tag is an empty tag, which means that, it can contain only list of attributes and it has
no closing tag.
Example
To try following example, let's keep our HTML file test.htm and image file test.png in the same
directory −
<!DOCTYPE html>
<html>
<head>
<title>Using Image in Webpage</title>
</head>
<body>
</html>
Simple Image Insert
You can use PNG, JPEG or GIF image file based on your comfort but make sure you specify
correct image file name in src attribute. Image name is always case sensitive.
The alt attribute is a mandatory attribute which specifies an alternate text for an image, if the
image cannot be displayed.
You can set image width and height based on your requirement using width and height attributes.
You can specify width and height of the image in terms of either pixels or percentage of its actual
size.
Example
<!DOCTYPE html>
<html>
<head>
<title>Set Image Width and Height</title>
</head>
</html>
By default, image will have a border around it, you can specify border thickness in terms of pixels
using border attribute. A thickness of 0 means, no border around the picture.
Example
<!DOCTYPE html>
<html>
<head>
<title>Set Image Border</title>
</head>
<body>
<p>Setting image Border</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3"/>
</body>
</html>
By default, image will align at the left side of the page, but you can use align attribute to set it in
the center or right.
<head>
<title>Set Image Alignment</title>
</head>
<body>
<p>Setting image Alignment</p>
<img src = "/html/images/test.png" alt = "Test Image" border = "3" align = "right"/>
</body>
</html>
The HTML tables are created using the <table> tag in which the <tr> tag is used to create table
rows and <td> tag is used to create data cells. The elements under <td> are regular and left
aligned by default
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title>
</head>
<body>
<table border = "1">
<tr>
<td>Row 1, Column 1</td>
<td>Row 1, Column 2</td>
</tr>
<tr>
<td>Row 2, Column 1</td>
<td>Row 2, Column 2</td>
</tr>
</table>
</body>
</html>
Here, the border is an attribute of <table> tag and it is used to put a border across all the cells. If
you do not need a border, then you can use border = "0".
Table Heading
Table heading can be defined using <th> tag. This tag will be put to replace <td> tag, which is
used to represent actual data cell. Normally you will put your top row as table heading as shown
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Header</title>
</head>
<body>
<table border = "1">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
<td>Shabbir Hussein</td>
<td>7000</td>
</tr>
</table>
</body>
</html>
Name Salary
There are two attributes called cellpadding and cellspacing which you will use to adjust the white
space in your table cells. The cellspacing attribute defines space between table cells, while
cellpadding represents the distance between cell borders and the content within a cell.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Cellpadding</title>
</head>
<body>
<table border = "1" cellpadding = "5" cellspacing = "5">
<tr>
<th>Name</th>
<th>Salary</th>
</tr>
<tr>
<td>Ramesh Raman</td>
<td>5000</td>
</tr>
<tr>
</html>
Name Salary
You will use colspan attribute if you want to merge two or more columns into a single column.
Similar way you will use rowspan if you want to merge two or more rows.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table Colspan/Rowspan</title>
</head>
<body>
<table border = "1">
Mr. TAFOPA 6-90-83-88-42 29
Academic year 2021/2022
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
<tr>
<td rowspan = "2">Row 1 Cell 1</td>
<td>Row 1 Cell 2</td>
<td>Row 1 Cell 3</td>
</tr>
<tr>
<td>Row 2 Cell 2</td>
<td>Row 2 Cell 3</td>
</tr>
<tr>
<td colspan = "3">Row 3 Cell 1</td>
</tr>
</table>
</body>
</html>
Row 3 Cell 1
Tables can be divided into three portions − a header, a body, and a foot. The head and foot are
rather similar to headers and footers in a word-processed document that remain the same for every
page, while the body is the main content holder of the table.
The three elements for separating the head, body, and foot of a table are −
A table may contain several <tbody> elements to indicate different pages or groups of data. But
it is notable that <thead> and <tfoot> tags should appear before <tbody>
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Table</title>
</head>
<body>
<table border = "1" width = "100%">
<thead>
<tr>
<td colspan = "4">This is the head of the table</td>
</tr>
</thead>
<tfoot>
<tr>
<td colspan = "4">This is the foot of the table</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</body>
</html>
<ul> − An unordered list. This will list items using plain bullets.
<ol> − An ordered list. This will use different schemes of numbers to list your items.
<dl> − A definition list. This arranges your items in the same way as they are arranged in
a dictionary.
An unordered list is a collection of related items that have no special order or sequence. This list
is created by using HTML <ul> tag. Each item in the list is marked with a bullet.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
Beetroot
Ginger
Potato
Radish
You can use type attribute for <ul> tag to specify the type of bullet you like. By default, it is a
disc. Following are the possible options −
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul type = "square">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</html>
Beetroot
Ginger
Potato
Radish
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul type = "circle">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
o Beetroot
o Ginger
o Potato
o Radish
If you are required to put your items in a numbered list instead of bulleted, then HTML ordered
list will be used. This list is created by using <ol> tag. The numbering starts at one and is
incremented by one for each successive ordered list element tagged with <li>.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
1. Beetroot
2. Ginger
3. Potato
4. Radish
You can use type attribute for <ol> tag to specify the type of numbering you like. By default, it
is a number. Following are the possible options −
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol type = "I">
</html>
I. Beetroot
II. Ginger
III. Potato
IV. Radish
HTML and XHTML supports a list style which is called definition lists where entries are listed
like in a dictionary or encyclopedia. The definition list is the ideal way to present a glossary, list
of terms, or other name/value list.
<dt> − A term
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Definition List</title>
</head>
<body>
<dl>
<dt><b>HTML</b></dt>
<dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt>
<dd>This stands for Hyper Text Transfer Protocol</dd>
</dl>
</body>
</html>
HTML
This stands for Hyper Text Markup Language
HTTP
This stands for Hyper Text Transfer Protocol
HTML Forms are required, when you want to collect some data from the site visitor. For example,
during user registration you would like to collect information such as name, email address, credit
card, etc.
There are various form elements available like text fields, textarea fields, drop-down menus, radio
buttons, checkboxes, etc.
The HTML <form> tag is used to create an HTML form and it has following syntax −
Form Attributes
Apart from common attributes, following is a list of the most frequently used form attributes −
1
action
2
method
Method to be used to upload data. The most frequently used are GET and POST methods.
3
target
Specify the target window or frame where the result of the script will be displayed. It
takes values like _blank, _self, _parent etc.
You can use the enctype attribute to specify how the browser encodes the data before it
sends it to the server. Possible values are −
mutlipart/form-data − This is used when you want to upload binary data in the form of
files like image, word file etc.
Note − You can refer to Perl & CGI for a detail on how form data upload works.
There are different types of form controls that you can use to collect data using HTML form −
Checkboxes Controls
Hidden Controls
Clickable Buttons
Single-line text input controls − This control is used for items that require only one line
of user input, such as search boxes or names. They are created using HTML <input> tag.
Multi-line text input controls − This is used when the user is required to give details that
may be longer than a single sentence. Multi-line input controls are created using
HTML <textarea> tag.
This control is used for items that require only one line of user input, such as search boxes or
names. They are created using HTML <input> tag.
Example
Here is a basic example of a single-line text input used to take first name and last name −
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
</head>
<body>
<form >
First name: <input type = "text" name = "first_name" />
<br>
Last name: <input type = "text" name = "last_name" />
</form>
</body>
</html>
Following is the list of attributes for <input> tag for creating text field.
1
type
Indicates the type of input control and for text input control it will be set to text.
2
name
Used to give a name to the control which is sent to the server to be recognized and get
the value.
3
value
4
size
5
maxlength
Allows to specify the maximum number of characters a user can enter into the text box.
This is also a single-line text input but it masks the character as soon as a user enters it. They are
also created using HTML <input>tag but type attribute is set to password.
Here is a basic example of a single-line password input used to take user password −
<!DOCTYPE html>
<html>
<head>
<title>Password Input Control</title>
</head>
<body>
<form >
User ID : <input type = "text" name = "user_id" />
<br>
Password: <input type = "password" name = "password" />
</form>
</body>
</html>
Attributes
Following is the list of attributes for <input> tag for creating password field.
1
type
Indicates the type of input control and for password input control it will be set
to password.
Used to give a name to the control which is sent to the server to be recognized and get
the value.
3
value
4
size
5
maxlength
Allows to specify the maximum number of characters a user can enter into the text box.
This is used when the user is required to give details that may be longer than a single sentence.
Multi-line input controls are created using HTML <textarea> tag.
Example
Here is a basic example of a multi-line text input used to take item description −
<!DOCTYPE html>
<html>
<head>
<title>Multiple-Line Input Control</title>
</head>
</html>
Attributes
1
name
Used to give a name to the control which is sent to the server to be recognized
and get the value.
2
rows
Checkbox Control
Checkboxes are used when more than one option is required to be selected. They are also created
using HTML <input> tag but type attribute is set to checkbox..
Example
<!DOCTYPE html>
<html>
<head>
<title>Checkbox Control</title>
</head>
<body>
<form>
<input type = "checkbox" name = "maths" value = "on"> Maths
<input type = "checkbox" name = "physics" value = "on"> Physics
</form>
</body>
</html>
Attributes
1
type
Indicates the type of input control and for checkbox input control it will be set
to checkbox..
2
name
Used to give a name to the control which is sent to the server to be recognized and get
the value.
3
value
4
checked
Radio buttons are used when out of many options, just one option is required to be selected. They
are also created using HTML <input> tag but type attribute is set to radio.
Example
Here is example HTML code for a form with two radio buttons −
<!DOCTYPE html>
<html>
<head>
<body>
<form>
<input type = "radio" name = "subject" value = "maths"> Maths
<input type = "radio" name = "subject" value = "physics"> Physics
</form>
</body>
</html>
Attributes
1
type
Indicates the type of input control and for checkbox input control it will be set to radio.
2
name
Used to give a name to the control which is sent to the server to be recognized and get
the value.
3
value
A select box, also called drop down box which provides option to list down various options in the
form of drop down list, from where a user can select one or more options.
Example
Here is example HTML code for a form with one drop down box
<!DOCTYPE html>
<html>
<head>
<title>Select Box Control</title>
</head>
<body>
<form>
<select name = "dropdown">
<option value = "Maths" selected>Maths</option>
<option value = "Physics">Physics</option>
</select>
</form>
</body>
</html>
Attributes
1
name
Used to give a name to the control which is sent to the server to be recognized and get
the value.
2
size
3
multiple
If set to "multiple" then allows a user to select multiple items from the menu.
1
value
The value that will be used if an option in the select box box is selected.
2
selected
Specifies that this option should be the initially selected value when the page loads.
3
label
If you want to allow a user to upload a file to your web site, you will need to use a file upload
box, also known as a file select box. This is also created using the <input> element but type
attribute is set to file.
Example
Here is example HTML code for a form with one file upload box −
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "file" name = "fileupload" accept = "image/*" />
</form>
</body>
</html>
Attributes
Used to give a name to the control which is sent to the server to be recognized
and get the value.
2
accept
Button Controls
There are various ways in HTML to create clickable buttons. You can also create a clickable
button using <input>tag by setting its type attribute to button. The type attribute can take the
following values −
1
submit
2
reset
This creates a button that automatically resets form controls to their initial values.
3
button
This creates a button that is used to trigger a client-side script when the user clicks
that button.
This creates a clickable button but we can use an image as background of the button.
Example
Here is example HTML code for a form with three types of buttons −
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
<input type = "button" name = "ok" value = "OK" />
<input type = "image" name = "imagebutton" src = "/html/images/logo.png" />
</form>
</body>
</html>
Hidden form controls are used to hide data inside the page which later on can be pushed to the
server. This control hides inside the code and does not appear on the actual page. For example,
following hidden form is being used to keep current page number. When a user will click next
Example
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
<body>
<form>
<p>This is page 10</p>
<input type = "hidden" name = "pagename" value = "10" />
<input type = "submit" name = "submit" value = "Submit" />
<input type = "reset" name = "reset" value = "Reset" />
</form>
</body>
</html>
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 the value
either red or #F1F1F1 etc.
Here table is a selector and border is a property and the given value 1px solid #C00 is the value of
that property.
You can define selectors in various simple ways based on your comfort. Let me put these selectors
one by one.
We have seen above this same selector. Again, one more example to give a color to all level 1
headings:
h1 { color: #36CFFF;
}
Rather than selecting elements of a specific type, the universal selector quite simply matches the
name of any element type:
*{ color: #000000;
}
This rule renders the content of every element in our document in black.
ul em { color: #000000;
}
You can define style rules based on the class attribute of the elements. All the elements having that
class will be formatted according to the defined rule.
This rule renders the content in black for every element with class attribute set to black in our
document. You can make it a bit more particular. For example:
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to a given element. Consider the following example:
</p>
The ID Selectors
This rule renders the content in black for every element with id attribute set to black in our
document. You can make it a bit more particular. For example:
This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendant selectors.
For example:
In this example, all level 2 headings will be displayed in black color when those headings will lie
within tags having id attribute set to black.
You have seen the descendant selectors. There is one more type of selector, which is very similar
to descendants but have different functionality. Consider the following example:
Grouping Selectors
You can apply a style to many selectors if you like. Just separate the selectors with a comma, as
given in the following example:
This define style rule will be applicable to h1, h2 and h3 element as well. The order of the list is
irrelevant. All the elements in the selector will have the corresponding declarations applied to
them.
You can combine the various class selectors together as shown below:
<head>
Style Rules
............
</style>
</head>
Attributes
media screen tty Specifies the device, the document will be displayed on.
tv Default value is all. This is an optional attribute.
projection
handheld
print
braille
aural
all
<head>
</head>
You can use style attribute of any HTML element to define style rules. These rules will be applied
to that element only. Here is the generic syntax:
Attributes
Example
The <link> element can be used to include an external stylesheet file in your HTML document.
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.
<head>
</head>
Attributes
type text/css Specifies the style sheet language as a content-type (MIME type).
This attribute is required.
media screen tty Specifies the device the document will be displayed on. Default
tv value is all. This is an optional attribute.
projection
handheld
print
braille
aural
all
Example
Consider a simple style sheet file with a name mystyle.css having the following rules:
Now you can include this file mystyle.css in any HTML document as follows:
<head>
</head>
@import is used to import an external stylesheet in a manner similar to the <link> element. Here
is the generic syntax of @import rule.
<head>
<@import "URL";
</head>
Here URL is the URL of the style sheet file having style rules. You can use another syntax as well:
<head>
<@import url("URL");
</head>
Example
Following is the example showing you how to import a style sheet file into an HTML document:
<head>
@import "mystyle.css";
</head>
CSS Comments
Many times, you may need to put additional comments in your style sheet blocks. So, it is very
easy to comment any part in the style sheet. You can simply put your comments inside /*.....this is
a comment in style sheet.....*/.
Example
/* This is an external style sheet file */ h1, h2, h3 { color: #36C; font-weight: normal; letter-
spacing: .4em; margin-bottom: 1em; text-transform: lowercase;
}
We have listed out all the CSS Measurement Units along with proper Examples:
Unit Description Example
You can specify your color values in various formats. Following table lists all the possible formats
A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red value,
the next two are a green value(GG), and the last are the blue value(BB).
A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc
Paintshop Pro, or even using Advanced Paint Brush.
Each hexadecimal code will be preceded by a pound or hash sign '#'. Following are the examples
to use Hexadecimal notation.
#000000
#FF0000
#00FF00
#0000FF
#FFFF00
#00FFFF
#FF00FF
#C0C0C0
#FFFFFF
OVERVIEW
What is JavaScript ?
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has
been embedded in Netscape, Internet Explorer, and other web browsers.
The ECMA-262 Specification defined a standard version of the core JavaScript language.
Client-Side JavaScript
Client-side JavaScript is the most common form of the language. The script should be included
in or referenced by an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with
the user, control the browser, and dynamically create HTML content.
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
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.
Limitations of JavaScript
Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
JavaScript cannot be used for networking applications because there is no such support
available.
Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
SYNTAX
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as
a script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
Language − This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.
Type − This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
ENABLING
All the modern browsers come with built-in support for JavaScript. Frequently, you may need to
enable or disable this support manually. This chapter explains the procedure of enabling and
disabling JavaScript support in your browsers: Internet Explorer, Firefox, chrome, and Opera.
Here are simple steps to turn on or turn off JavaScript in your Internet Explorer −
To disable JavaScript support in your Internet Explorer, you need to select Disable radio button
under Active scripting.
JavaScript in Firefox
Then you will find the warning dialog. Select I’ll be careful, I promise!
Then you will find the list of configure options in the browser.
There you will find the option to enable or disable javascript by right-clicking on the value
of that option → select toggle.
If JavaScript Enabled is true; it converts to false upon clicking toogle. If javascript is disabled; it
gets enabled upon clicking toggle.
JavaScript in Chrome
Click the Chrome menu at the top right hand corner of your browser.
Select Settings.
In the "Javascript" section, select "Do not allow any site to run JavaScript" or "Allow all
sites to run JavaScript (recommended)".
PLACEMENT
There is a flexibility given to include JavaScript code anywhere in an HTML document. However
the most preferred ways to include JavaScript in an HTML file are as follows −
If you want to have a script run on some event, such as when a user clicks somewhere, then you
will place that script in the head as follows –
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
If you need a script to run as the page loads so that the script generates content in the page, then
the script goes in the <body> portion of the document. In this case, you would not have any
function defined using JavaScript. Take a look at the following code.
<html>
<body>
<script type = "text/javascript">
<!--
document.write("Hello World")
//-->
</script>
You can put your JavaScript code in <head> and <body> section altogether as follows ;
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type = "text/javascript">
As you begin to work more extensively with JavaScript, you will be likely to find that there are
cases where you are reusing identical JavaScript code on multiple pages of a site.
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>
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")
}
VARIABLES
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.
You can also declare multiple variables with the same var keyword as follows −
For instance, you might create a variable named money and assign the value 2000.50 to it later.
For another variable, you can assign a value at the time of initialization as follows.
Note − Use the var keyword only for declaration or initialization, once for the life of any variable
name in a document. You should not re-declare same variable twice.
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.
The scope of a variable is the region of your program in which it is defined. JavaScript variables
have only two scopes.
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.
Within the body of a function, a local variable takes precedence over a global variable with the
same name. If you declare a local variable or function parameter with the same name as a global
variable, you effectively hide the global variable. Take a look into the following example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>
local
While naming your variables in JavaScript, keep the following rules in mind.
You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable
names are not valid.
JavaScript variable names should not start with a numeral (0-9). They must begin with a
letter or an underscore character. For example, 123test is an invalid variable name
but _123test is a valid one.
JavaScript variable names are case-sensitive. For example, Name and name are two
different variables.
A list of all the reserved words in JavaScript are given in the following table. They cannot be used
as JavaScript variables, functions, methods, loop labels, or any object names.
double in super
OPERATORS
What is an Operator?
Let us take a simple expression 4 + 5 is equal to 9. Here 4 and 5 are called operands and ‘+’ is
called the operator. JavaScript supports the following types of operators.
Arithmetic Operators
Comparison Operators
Assignment Operators
Arithmetic Operators
1
+ (Addition)
2
- (Subtraction)
3
* (Multiplication)
4
/ (Division)
5
% (Modulus)
7
-- (Decrement)
Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Example
<html>
<body>
document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);
document.write("a - b = ");
document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);
document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);
document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);
a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);
b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
Output
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8
Set the variables to different values and then try...
Comparison Operators
1
= = (Equal)
Checks if the value of two operands are equal or not, if yes, then the condition becomes
true.
Checks if the value of two operands are equal or not, if the values are not equal, then
the condition becomes true.
Ex: (A != B) is true.
3
> (Greater than)
Checks if the value of the left operand is greater than the value of the right operand, if
yes, then the condition becomes true.
4
< (Less than)
Checks if the value of the left operand is less than the value of the right operand, if
yes, then the condition becomes true.
5
>= (Greater than or Equal to)
Checks if the value of the left operand is greater than or equal to the value of the right
operand, if yes, then the condition becomes true.
6
<= (Less than or Equal to)
Checks if the value of the left operand is less than or equal to the value of the right
operand, if yes, then the condition becomes true.
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";
Output
(a == b) => false
(a < b) => true
(a > b) => false
(a != b) => true
(a >= b) => false
a <= b) => true
Set the variables to different values and different operators and then try...
Logical Operators
1
&& (Logical AND)
If both the operands are non-zero, then the condition becomes true.
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.
Example
Try the following code to learn how to implement Logical Operators in JavaScript.
<html>
<body>
<script type = "text/javascript">
<!--
var a = true;
var b = false;
var linebreak = "<br />";
Output
(a && b) => false
(a || b) => true
!(a && b) => true
Set the variables to different values and different operators and then try...
Bitwise Operators
1
& (Bitwise AND)
Ex: (A & B) is 2.
2
| (BitWise OR)
Ex: (A | B) is 3.
3
^ (Bitwise XOR)
Ex: (A ^ B) is 1.
4
~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand.
5
<< (Left Shift)
It moves all the bits in its first operand to the left by the number of places specified in
the second operand. New bits are filled with zeros. Shifting a value left by one position
Ex: (A << 1) is 4.
6
>> (Right Shift)
Binary Right Shift Operator. The left operand’s value is moved right by the number of
bits specified by the right operand.
Ex: (A >> 1) is 1.
7
>>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are
always zero.
Ex: (A >>> 1) is 1.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";
Assignment Operators
1
= (Simple Assignment )
Assigns values from the right side operand to the left side operand
2
+= (Add and Assignment)
It adds the right operand to the left operand and assigns the result to the left operand.
Ex: C += A is equivalent to C = C + A
3
−= (Subtract and Assignment)
It subtracts the right operand from the left operand and assigns the result to the left
operand.
Ex: C -= A is equivalent to C = C - A
It multiplies the right operand with the left operand and assigns the result to the left
operand.
Ex: C *= A is equivalent to C = C * A
5
/= (Divide and Assignment)
It divides the left operand with the right operand and assigns the result to the left
operand.
Ex: C /= A is equivalent to C = C / A
6
%= (Modules and Assignment)
It takes modulus using two operands and assigns the result to the left operand.
Ex: C %= A is equivalent to C = C % A
Note − Same logic applies to Bitwise operators so they will become like <<=, >>=, >>=, &=, |=
and ^=.
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 33;
var b = 10;
var linebreak = "<br />";
Output
Value of a => (a = b) => 10
Value of a => (a += b) => 20
Value of a => (a -= b) => 10
Value of a => (a *= b) => 100
Value of a => (a /= b) => 10
Value of a => (a %= b) => 0
Set the variables to different values and different operators and then try...
Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (?
:) and the typeof operator.
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 )
Example
Try the following code to understand how the Conditional Operator works in JavaScript.
<html>
Output
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100
Set the variables to different values and different operators and then try...
typeof Operator
The 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.
Number "number"
String "string"
Boolean "boolean"
Object "object"
Function "function"
Undefined "undefined"
Null "object"
Example
<html>
<body>
<script type = "text/javascript">
<!--
var a = 10;
Output
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then try...
if statement
if...else statement
The if statement is the fundamental control statement that allows JavaScript to make decisions
and execute statements conditionally.
Syntax
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
<html>
<body>
<script type = "text/javascript">
<!--
var age = 20;
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.
<html>
<body>
<script type = "text/javascript">
<!--
var age = 15;
The if...else if... statement is an advanced form of if…else that allows JavaScript to make a
correct decision out of several conditions.
Syntax
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.
<html>
<body>
<script type = "text/javascript">
<!--
var book = "maths";
Flow Chart
Syntax
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;
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
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
break;
Output
Entering switch block
Good job
Exiting switch block
Set the variable to different value and then try...
Break statements play a major role in switch-case statements. Try the following code that uses
switch-case statement without any break statement.
<html>
<body>
<script type = "text/javascript">
<!--
var grade = 'A';
document.write("Entering switch block<br />");
switch (grade) {
case 'A': document.write("Good job<br />");
case 'B': document.write("Pretty good<br />");
case 'C': document.write("Passed<br />");
case 'D': document.write("Not so good<br />");
JavaScript – events
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.
Please go through this small tutorial for a better understanding HTML Event Reference. Here we
will see a few examples to understand a relation between Event and JavaScript −
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
<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>
Output
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.
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() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
<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>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Output
The standard HTML 5 events are listed here for your reference. Here script indicates a Javascript
function to be executed against that event.
Triggers when media can start play, but might has to stop for
oncanplay script
buffering
ondragenter script Triggers when an element has been dragged to a valid drop target
onmouseout script Triggers when the mouse pointer moves out of an element
onmouseover script Triggers when the mouse pointer moves over an element
onprogress script Triggers when the browser is fetching the media data
onratechange script Triggers when the media data's playing rate has changed
Triggers when the browser has been fetching media data, but
onsuspend script
stopped before the entire media file was fetched
JavaScript cookies
Web Browsers and Servers use HTTP protocol to communicate and HTTP 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 completing many pages. But how to maintain
users' session information across all the web pages.
In many situations, using cookies is the most efficient method of remembering and tracking
preferences, purchases, commissions, and other information required for better visitor 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. Now,
when the visitor arrives at another page on your site, the browser sends the same cookie to the
server for retrieval. Once retrieved, your server knows/remembers what was stored earlier.
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. This may be blank if you
want to retrieve the cookie from any directory or page.
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.
Name=Value − Cookies are set and retrieved in the form of key-value pairs
JavaScript can also manipulate cookies using the cookie property of the Document object.
JavaScript can read, create, modify, and delete the cookies that apply to the current web page.
Storing Cookies
The simplest way to create a cookie is to assign a string value to the document.cookie object,
which looks like this.
Here the expires attribute is optional. If you provide this attribute with a valid date or time, then
the cookie will expire on a given date or time and thereafter, the cookies' value will not be
accessible.
Note − Cookie values may not include semicolons, commas, or whitespace. For this reason, you
may want to use the JavaScript escape() function to encode the value before storing it in the
cookie. If you do this, you will also have to use the corresponding unescape() function when you
read the cookie value.
Example
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
Output
Now your machine has a cookie called name. You can set multiple cookies using multiple key =
value pairs separated by comma.
Reading Cookies
Reading a cookie is just as simple as writing one, because the value of the document.cookie object
is the cookie. So you can use this string whenever you want to access the cookie. The
document.cookie string will keep a list of name=value pairs separated by semicolons,
where name is the name of a cookie and value is its string value.
You can use strings' split() function to break a string into key and values as follows −
Example
<body>
<form name = "myform" action = "">
<p> click the following button and see the result:</p>
<input type = "button" value = "Get Cookie" onclick = "ReadCookie()"/>
</form>
</body>
</html>
Note − There may be some other cookies already set on your machine. The above code will
display all the cookies set on your machine.
You can extend the life of a cookie beyond the current browser session by setting an expiration
date and saving the expiry date within the cookie. This can be done by setting
the ‘expires’ attribute to a date and time.
Example
Try the following example. It illustrates how to extend the expiry date of a cookie by 1 Month.
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() + 1 );
cookievalue = escape(document.myform.customer.value) + ";"
Output
Deleting a Cookie
Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return
nothing. To do this, you just need to set the expiry date to a time in the past.
Example
Try the following example. It illustrates how to delete a cookie by setting its expiry date to one
month behind the current date.
Live Demo
<html>
<head>
<script type = "text/javascript">
<!--
function WriteCookie() {
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = escape(document.myform.customer.value) + ";"
<body>
<form name = "myform" action = "">
Enter name: <input type = "text" name = "customer"/>
<input type = "button" value = "Set Cookie" onclick = "WriteCookie()"/>
</form>
</body>
</html>
You might have encountered a situation where you clicked a URL to reach a page X but internally
you were directed to another page Y. It happens due to page redirection. This concept is different
from JavaScript Page Refresh.
There could be various reasons why you would like to redirect a user from the original page. We
are listing down a few of the reasons −
You did not like the name of your domain and you are moving to a new one. In such a
scenario, you may want to direct all your visitors to the new site. Here you can maintain
your old domain but put a single page with a page redirection such that all your old domain
visitors can come to your new domain.
You have built-up various pages based on browser versions or their names or may be based
on different countries, then instead of using your server-side page redirection, you can use
client-side page redirection to land your users on the appropriate page.
Example 1
It is quite simple to do a page redirect using JavaScript at client side. To redirect your site visitors
to a new page, you just need to add a line in your head section as follows.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
//-->
</script>
</head>
<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
Example 2
You can show an appropriate message to your site visitors before redirecting them to a new page.
This would need a bit time delay to load a new page. The following example shows how to
implement the same. Here setTimeout() is a built-in JavaScript function which can be used to
execute another function after a given time interval.
<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.tutorialspoint.com";
}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>
<body>
</body>
</html>
Output
You will be redirected to tutorialspoint.com main page in 10 seconds!
Example 3
The following example shows how to redirect your site visitors onto a different page based on
their browsers.
<html>
<body>
</body>
</html>