0% found this document useful (1 vote)
482 views78 pages

Web Notes

Html

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
482 views78 pages

Web Notes

Html

Uploaded by

Leslie Qwer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Web Programming Notes B .

Sc CS

WEB PROGRAMMING

1 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

CS1242: WEB PROGRAMMING :- SYLLABUS

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

2 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

MODULE I
HTML

3 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

Some common definitions given in the past include −

 A network of networks based on the TCP/IP communications protocol.

 A community of people who use and develop those networks.

 A community of people who use and develop those networks.

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.

 World Wide Web (WWW) − A hypertext interface to Internet information resources.

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.

4 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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).

A URL will have the following format −


protocol://hostname/other_information

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 Web Server?


 Every Website sits on a computer known as a Web server. This server is always
connected to the internet. Every Web server that is connected to the Internet is given a
unique address made up of a series of four numbers between 0 and 256 separated by
periods. For example, 68.178.157.132 or 68.122.35.127.
 When you register a Web address, also known as a domain name, such as
tutorialspoint.com you have to specify the IP address of the Web server that will host
the site.
 We will see different type of Web servers in a separate chapter.

5 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

What is Web Browser?


 Web Browsers are software installed on your PC. To access the Web you need a web
browsers, such as Netscape Navigator, Microsoft Internet Explorer or Mozilla Firefox.

What is SMTP Server?


 SMTP stands for Simple Mail Transfer Protocol Server. This server takes care of
delivering emails from one server to another server. When you send an email to an
email address, it is delivered to its recipient by a SMTP Server.

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.

6 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

 HTML is the standard markup language for creating Web pages.


 HTML stands for Hyper Text Markup Language
 HTML describes the structure of Web pages using markup
 HTML elements are the building blocks of HTML pages
 HTML elements are represented by tags
 HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
 Browsers do not display the HTML tags, but use them to render the content of the page

Basic HTML Document


<html>

<head>
<title>This is document title</title>
</head>

<body>
<h1>This is a heading</h1>
<p>Document content goes here.....</p>
</body>

</html>

Types of Documents in 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

7 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

1.HTML 4.01 Strict

This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or
deprecated elements (like font). Framesets are not allowed.

2.HTML 4.01 Transitional

This DTD contains all HTML elements and attributes, INCLUDING presentational and
deprecated elements (like font). Framesets are not allowed.

3..HTML 4.01 Frameset

This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.

4.XHTML 1.0 Strict

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.

5.XHTML 1.0 Transitional

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).

8 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML Tags
As told earlier, HTML is a markup language and makes use of various tags to format the
content.

HTML Text- Formatting Elements / Text level elements

 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.

<b>This text is bold</b>

2.<strong> - Important text, The HTML <strong> element defines strong text, with added
semantic "strong" importance.

<strong>This text is strong</strong>

3.<i> - Italic text, The HTML <i> element defines italic text, without any extra importance.

<i>This text is italic</i>

4.<em> - Emphasized text, The HTML <em> element defines emphasized text, with added
semantic importance.

<em>This text is emphasized</em>

5.<sub> - Subscript text ,The HTML <sub> element defines subscripted text.

<p>This is <sub>subscripted</sub> text.</p>

6.<sup> - Superscript text, The HTML <sup> element defines superscripted text.

<p>This is <sup>superscripted</sup> text.</p>

9 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Illustration of Text formatting tags


This has some <B>bold text</B>.
I italic text style
The quick red fox jumped over the lazy brown dog.
B bold text style
The quick red fox jumped over the lazy brown dog.
U underlined text style
The quick red fox jumped over the lazy brown dog.
STRIKE strike-through text style
The quick red fox jumped over the lazy brown dog.
BIG places text in a large font
The quick red fox jumped over the lazy brown dog.
SMALL places text in a small font
The quick red fox jumped over the lazy brown dog.
SUB places text in subscript style
The foxred jumped over the dogbrown.
SUP places text in superscript style
The foxquick jumped over the doglazy

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.

Frequently Used HTML Character Entities

Result Description Entity Name Numerical reference

non-breaking space &nbsp; &#160;

< less than &lt; &#60;

> greater than &gt; &#62;

10 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

& ampersand &amp; &#38;

" quotation mark &quot; &#34;

© copyright &copy; &#169;

HTML <video> Tag


The <video> tag specifies video, such as a movie clip or other video streams.Currently, there are 3
supported video formats for the <video> element: MP4, WebM, and Ogg:

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
</video>

HTML <audio> Tag


Play a sound: the <audio> tag defines sound, such as music or other audio streams.Currently, there
are 3 supported file formats for the <audio> element: MP3, WAV, and OGG:

<audio controls>
<source src="horse.mp3" type="audio/mpeg">
</audio>

HTML <head> Tag

The <head> element is a container for all the head elements.

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:

<title> (this element is required in an HTML document)

<style>

<base>

<link>

<script>

11 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Example

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>

HTML Heading Tag

The <h1> to <h6> tags are used to define HTML headings.<h1> defines the most important
heading. <h6> defines the least important heading.

<h1>This is heading 1</h1>


<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

HTML <body> Tag

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>

12 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML <div> Tag

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.

<div style="background-color: blue">


<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>

HTML <center> Tag

The <center> tag is used to center-align text.

<center>This text will be center-aligned.</center>

HTML <q> Tag

The <q> tag defines a short quotation.

Browsers normally insert quotation marks around the quotation.

<q>Build a future where people live in harmony with nature.</q>

HTML <li> Tag (List)

The <li> tag defines a list item.

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>

13 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML <hr> Tag

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>

14 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Grouping HTML Elements

There are two important tags which we use very frequently to group various other HTML tags
(i) <div> tag and (ii) <span> tag

1.The <div> 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

Following is a simple example of <div> tag.

<!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>

<!-- Second group of tags -->


<div style = "color:green">
<h4>This is second group</h4>
<p>Following is a list of fruits</p>
</div>
</body>

</html>

15 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

2.The <span> tag

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>

HTML <table> Tag


 The <table> tag defines an HTML table.
 An HTML table consists of the <table> element and one or more <tr>, <th>,
and <td> elements.
 The <tr> element defines a table row,
 the <th> element defines a table header,
 the <td> element defines a table cell.

<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>

16 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Comment - <!-- -->


Anything between the comment tags is not displayed by the browser, so they are used to document
your html code, or sometimes for hiding sections of html that you don't want to delete just yet.

Example 1 : Single Line

<!-- Or you can comment out a large number of lines. -->

Example 2: Multi line

<!—
Or you can
comment out a large
number of lines.
-->

HTML <font> Tag.

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>

HTML <marquee> Tag

 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:

 <marquee>A scrolling text created with HTML Marquee element.</marquee>


 <marquee direction="down">A scrolling text created with HTML Marquee element.
 <marquee direction=”right">A scrolling text created with HTML Marquee element.

17 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

MODULE II
Advanced HTML

18 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML Links – Hyperlinks / Anchor Tag


 HTML links are hyperlinks.
 You can click on a link and jump to another document.
 When you move the mouse over a link, the mouse arrow will turn into a little hand.
 In HTML, links are defined with the <a> tag

 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>

Eg : <a href=https://www.macas.in”/> Visit our Webite</a>

 The href attribute specifies the destination address (https://www.w3schools.com/html/) of


the link.
 The link text is the visible part (Visit our HTML tutorial).

HTML Links - Image as Link


It is common to use images as links:

<a href="www.macas.in"> <img src="pic.jpg" ></a>

 Use the <a> element to define a link


 Use the href attribute to define the link address
 Use the <img> element (inside <a>) to use an image as a link

HTML - Frames
HTML frames are used to divide your browser window into multiple sections where each
section can load a separate HTML document.

A collection of frames in the browser window is known as a frameset. The window is


divided into frames in a similar way the tables are organized: into rows and columns.

<frameset rows = "10%,80%,10%">


<frame name = "top" src = "page1.htm" />
<frame name = "main" src = "page2.htm" />
<frame name = "bottom" src = "page3htm" />
</frameset>

19 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

<img src="planets.gif" width="145" height="126" usemap="#planetmap">


<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="map1.htm" >
<area shape="circle" coords="90,58,3" href="map2.htm" >
<area shape="circle" coords="124,58,8" href="map3.htm">
</map>

Uniform Resource Locator (URL) and it’s Types

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

What is the difference between an absolute and a relative URL?

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

20 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Linking with absolute URLs


An absolute URL typically takes the following form:
protocol: //domain/path
Example
http://www.macas.in/fac.html

 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.

Linking with relative URLs


Relative URLs can take a number of different forms. When referring to a file that occurs in the
same directory as the referring page, a URL can be as simple as the name of the file.
For example, if you want to create a link in your home page to the file home.html,
<a href="home.html">HOME PAGE</a>

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:

<a href="macas/fac.html">View Faculty List</a>

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;">

21 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

The alt Attribute


 The alt attribute provides an alternate text for an image,
 The value of the alt attribute should describe the image:

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).

22 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML5 offers new semantic elements that define the different parts of a web page:

HTML <a> target Attribute


The target attribute specifies where to open the linked document.
Example
<a href="https://www.macas.in/fac.html" target="_blank">View faculty Details</a>
Attribute Values

Value Description

_blank Opens the linked document in a new window or tab

_self Opens the linked document in the same frame as it was clicked
(this is default)

_parent Opens the linked document in the parent frame

_top Opens the linked document in the full body of the window

23 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

HTML <noframes> Tag.


 The <noframes> tag is a fallback tag for browsers that do not support frames. It can contain all the
HTML elements that you can find inside the <body> element of a normal HTML page.
 The <noframes> element can be used to link to a non-frameset version of the web site or to display a
message to users that frames are required.
 The <noframes> element goes inside the <frameset> element.

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

HTML <iframe> align Attribute (Floating tag)


The <iframe> element is an inline element (it does not insert a new line on a page), meaning that text and other
elements can wrap around it. Therefore, it can be useful to specify the alignment of the <iframe> according to
surrounding elements.
<iframe src="/insidepage.html" width="200" height="200" align="right">
</iframe>

24 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

The HTML <form> tag


 The HTML <form> tag is used for creating a form for user input. A form can contain
textfields, checkboxes, radio-buttons and more. Forms are used to pass user-data to a
specified URL.
 The <form> tag is used to create an HTML form for user input.
 The <form> element can contain one or more of the following form elements:

<input> <textarea> <button> <select> <option> <label>


Example
<form action="/page1.php" method="get">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
Form Field Attributes
This table shows the attributes that are specific to the <form> tag/element.

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).

The autocomplete attribute is an enumerated attribute which has two states;


"on" and "off". The default value is "on".

enctype Specifies the content type used to encode the form data set when it's submitted
to the server.

25 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.)

name Assigns a name to the form.

novalidate Specifies that the form should not be validated during submission.

target Specifies the browsing context to load the destination indicated in


the action attribute.

Possible values:

 _blank
 _self
 _top
 _parent

GET and POST Methods


You must have come across many situations when you need to pass some information from
your browser to the web server and CGI Program handling your requests. Most frequently
browser uses two methods to pass this information to the web server. These methods
are GET Method and POST Method.

Passing Information using GET Method


 The GET method sends the encoded user information appended to the page URL itself.
The page and the encoded information are separated by the ? character as follows −
 http://www.test.com/cgi-bin/hello.cgi?key1=value1&key2=value2
 The GET method is the defualt method to pass information from a browser to the web
server and it produces a long string.
 You should never use GET method if you have password or other sensitive information
to pass to the server.

26 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

 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.

Simple URL Example: Get Method


<FORM action = "page2.php" method = "GET">

First Name: <input type = "text" name = "first_name">


Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</FORM>

Passing Information using POST Method


A more reliable method of passing information to a CGI program is the POSTmethod. This
packages the information in exactly the same way as GET methods, but instead of sending it as
a text string after a ? in the URL, it sends it as a separate message as a part of HTTP header.
Web server provides this message to the CGI script in the form of the standard input.

<FORM action = "page2.php" method = "POST">


First Name: <input type = "text" name = "first_name"> <br>
Last Name: <input type = "text" name = "last_name">
<input type = "submit" value = "Submit">
</FORM>

HTML accesskey Attribute


The accesskey attribute specifies a shortcut key to activate/focus an element.

<a href="https://www.macas.in" accesskey="m">MACAS</a><br>

<a href="https://www.keralayniversity.ac.in" accesskey="u">UNIVERSITY</a>

Syntax : [Alt] + accesskey

Example : Alt+m

27 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

How To Create Tooltips

Step 1) : Write HTML


Example
<div>Hover over me
<span class="tooltiptext">Tooltip text</span>
</div>
Step 2) Write CSS:

.tooltiptext
{
width: 120px;
background-color: red;
color: black;
text-align: center;
border-radius: 6px;

28 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

MODULE III
Javascript

29 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

 JavaScript is a lightweight, interpreted programming language.

 Designed for creating dynamic web applications.

 Complementary to and integrated with HTML.

 Open and cross-platform

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.

30 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

 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.

Implementation of Java script in HTML Page.


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 −

1. Script in <head>...</head> section.

2. Script in <body>...</body> section.

3. Script in <body>...</body> and <head>...</head> sections.

4. Script in an external file and then include in <head>...</head> section.

1.JavaScript in <head>...</head> section


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 −
Lemo
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

31 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>

2.JavaScript in <body>...</body> section


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.
Live Demo
<html>
<head>
</head>

<body>
<script type = "text/javascript">
document.write("Hello World")
</script>

<p>This is web page body </p>


</body>
</html>

32 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

3.JavaScript in <body> and <head> Sections


You can put your JavaScript code in <head> and <body> section altogether as follows −
Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>

<body>
<script type = "text/javascript">

document.write("Hello World")
</script>

<input type = "button" onclick = "sayHello()" value = "Say Hello" />


</body>
</html>

33 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

4.JavaScript in External File


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>
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.

34 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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 Data types


One of the most fundamental characteristics of a programming language is the set of data
types it supports. These are the type of values that can be represented and manipulated in a
programming language.

JavaScript allows you to work with three primitive data types −

 Numbers, eg. 123, 120.50 etc.

 Strings of text e.g. "This text string" etc.

 Boolean e.g. true or false.

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.

<script type = "text/javascript">


var money;
var name;
</script>
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
var money, name;
</script>

35 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

You can assign a value at the time of initialization as follows.

<script type = "text/javascript">


var name = "Ali";
var money;
money = 2000.50;
</script>

JavaScript Variable Scope


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.

Operators in Java Script


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.

1. Arithmetic Operators

2. Comparison Operators

3. Logical (or Relational) Operators

4. Assignment Operators

5. Conditional (or ternary) Operators

1.Arithmetic Operators
JavaScript supports the following arithmetic operators − Assume variable A holds 10 and
variable B holds 20, then −

Sr.No Operator and Description

1 + (Addition)
Adds two operands
Ex: A + B will give 30

36 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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 −

Sr.No Operator and Description

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,

37 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.
Ex: (A > B) is not 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.
Ex: (A < B) is 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.
Ex: (A >= B) is not 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.
Ex: (A <= B) is true.

3.Logical Operators
JavaScript supports the following logical operators −Assume variable A holds 10 and variable B
holds 20, then −

Sr.No Operator and Description

1 && (Logical AND)


If both the operands are non-zero, then the condition becomes true.
Ex: (A && B) is true.

2 || (Logical OR)
If any of the two operands are non-zero, then the condition becomes true.
Ex: (A || B) is true.

38 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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 −

Sr.No Operator and Description

1 & (Bitwise AND)


It performs a Boolean AND operation on each bit of its integer arguments.
Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments.
Ex: (A | B) is 3.

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 is equivalent to multiplying it by 2, shifting two positions is
equivalent to multiplying by 4, and so on.
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.

39 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

5.Assignment Operators
JavaScript supports the following assignment operators −

Sr.No Operator and Description

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

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

4 *= (Multiply and Assignment)


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

Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional
operator (? :) and the typeof operator.

40 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

Sr.No Operator and Description

1 ? : (Conditional )

If Condition is true? Then value X : Otherwise value Y

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.

Here is a list of the return values for the typeof Operator.

Conditional Statements in JAVASCRIPT


JavaScript supports the following forms of if..else statement −

1. if statement

2. if...else statement

3. if...else if... 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.

41 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Example
Try the following example to understand how the if statement works.

<script type = "text/javascript">

var age = 20;

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}
</script>
Output
Qualifies for driving
Set the variable to different value and then try...

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.

<script type = "text/javascript">

var age = 15;

42 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

if( age > 18 )


{
document.write("<b>Qualifies for driving</b>");
}
else
{
document.write("<b>Does not qualify for driving</b>");
}
</script>
Output
Does not qualify for driving
Set the variable to different value and then try...

3. if...else if... statement


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
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.

43 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Example
Try the following code to learn how to implement an if-else-if statement in JavaScript.

<script type = "text/javascript">


var book = "maths";
if( book == "history" )
{
document.write("<b>History Book</b>");
}
else if( book == "maths" )
{
document.write("<b>Maths Book</b>");
}
else if( book == "economics" )
{
document.write("<b>Economics Book</b>");
}
Else
{
document.write("<b>Unknown Book</b>");
}
</script>

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.

44 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

We will explain break statement in Loop Control chapter.

Example
Try the following example to implement switch-case statement.

<script type = "text/javascript">


var grade = 'A';
document.write("Entering switch block<br />");
switch (grade)
{
case 'A':
document.write("Good job<br />");
break;

case 'B':
document.write("Pretty good<br />");
break;

case 'C':
document.write("Passed<br />");
break;

case 'D':

45 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

document.write("Not so good<br />");


break;

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.

1.The while Loop


The most basic loop in JavaScript is the while loop which would be discussed in this chapter.
The purpose of a while loop is to execute a statement or code block repeatedly as long as
an expression is true. Once the expression becomes false, the loop terminates.

Syntax
The syntax of while loop in JavaScript is as follows −

while (expression)
{
Statement(s) to be executed if expression is true
}

46 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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

2. The do...while Loop


The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the
condition is false.
Syntax
The syntax for do-while loop in JavaScript is as follows −

Do
{
Statement(s) to be executed;
}
while (expression);

47 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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 −

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}

48 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Example
Try the following example to learn how a for loop works in JavaScript.

<script type = "text/javascript">


var i;

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


{
document.write( i );
document.write("<br />");
}
</script>

Output
1
2
3
4

The break Statement


The break statement, which was briefly introduced with the switch statement, is used to exit a
loop early, breaking out of the enclosing curly braces.

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>

49 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Output
1
2
3
4
5

The continue Statement


The continue statement tells the interpreter to immediately start the next iteration of the loop
and skip the remaining code block. When a continuestatement is encountered, the program
flow moves to the loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.

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

50 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

51 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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

<p>Use different text in write method and then try...</p>


</body>
</html>

Event Driven Programming In JAVASCRIPT

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 −

52 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

1. onclick Event Type


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.

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.

Try the following example.

<html>
<head>

53 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

<script type="text/javascript">
function validation()
{

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>

3.onmouseover and onmouseout


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
the onmouseout triggers when you move your mouse out from that element. Try the
following example.

<html>
<head>

<script type="text/javascript">

function over()
{
document.write ("Mouse Over");
}

function out()
{
document.write ("Mouse Out");
}

</script>

54 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

</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>

Types of Dialog Boxes in JavaScript


JavaScript supports three important types of dialog boxes. These dialog boxes can be used to
raise an alert, or to get confirmation on any input or to have a kind of input from the users.
Here we will discuss each dialog box one by one.
1.Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users. For example, if one
input field requires to enter some text but the user does not provide any input, then as a part
of validation, you can use an alert box to give a warning message.

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>

55 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

<form>
<input type="button" value="Click Me" onclick="Warn();" />
</form>

</body>
</html>
Output

2.Confirmation Dialog Box


A confirmation dialog box is mostly used to take user's consent on any option. It displays a
dialog box with two buttons: Cancel.

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()
{

56 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

var retVal = confirm("Do you want to continue ?");


if( retVal == true )
{
document.write ("User wants to continue!");
return true;
}
Else
{
document.write ("User does not want to continue!");
return false;
}
}
</script>

</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

3.Prompt Dialog Box

57 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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>

58 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Output

Array in Java Script


The Array object lets you store multiple values in a single variable. It stores a fixed-size
sequential collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of the same
type.

Syntax
Use the following syntax to create an Array object −

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


The Array parameter is a list of strings or integers. When you specify a single numeric
parameter with the Array constructor, you specify the initial length of the array. The maximum
length allowed for an array is 4,294,967,295.

You can create array by simply assigning values as follows −

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

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

59 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

a[0] is the first element


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

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

Sr.No. Property & Description

1 constructor

Returns a reference to the array function that created the object.

2 index

The property represents the zero-based index of the match in the string

3 input

This property is only present in arrays created by regular expression matches.

4 length

Reflects the number of elements in an array.

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.

The syntax for adding a property to an object is −

60 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

objectName.objectProperty = propertyValue;

For example − The following code gets the document title using the "title"property of
the document object.

var str = document.title;

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

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)

61 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Dynamic Hypertext Markup Language-DHTML


 Dynamic HTML or DHTML, is a collection of technologies used together to create
interactive and animated web sites by using a combination of a HTML and CSS or
JavaScript.
 DHTML allows scripting languages to change variables in a web page's definition
language, which in turn affects the look and function of otherwise "static" HTML page
content, after the page has been fully loaded and during the viewing process.
 Thus the dynamic characteristic of DHTML is the way it functions while a page is viewed,
not in its ability to generate a unique page with each page load.
 DHTML allows authors to add effects to their pages that are otherwise difficult to
achieve. For example, DHTML allows the page author to:
 Animate text and images in their document, independently moving each element from
any starting point to any ending point, following a predetermined path or one chosen by
the user.
 Use a form to capture user input, and then process and respond to that data without
having to send data back to the server.
 Include rollover buttons or drop-down menus.

Page Redirect using Javascript


You can redirect a web page to another page in a number of ways including server-side redirects,
1. Sets the new location of the current window.
window.location = "https://www.example.com";
2. Sets the new href (URL) for the current window.
window.location.href = "https://www.example.com";
3. Assigns a new URL to the current window.
window.location.assign(https://www.example.com);
4. Replaces the location of the current window with the new one.
window.location.replace("https://www.example.com");
5. Sets the location of the current window itself.
self.location = "https://www.example.com";

62 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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>

JavaScript - Page Printing


 JavaScript helps you to implement this functionality using the print function of window object.
 The JavaScript print function window.print() prints the current web page when executed. You can call
this function directly using the onclick event as shown in the following example.

<html>

<body>
<form>
<input type = "button" value = "Print" onclick = "window.print()" />
</form>
</body>
<html>

63 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

String Methods and Properties in JavaScript


In JavaScript, methods and properties are also available to primitive values, because JavaScript
treats primitive values as objects when executing methods and properties.

1.String Length :-The length property returns the length of a string:

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)

64 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

The slice() Method

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 substring() Method

substring() is similar to slice().


The difference is that substring() cannot accept negative indexes.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13);
The result of res will be:Banana

The substr() Method

substr() is similar to slice().


The difference is that the second parameter specifies the length of the extracted part.
Example
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6);
The result of res will be:Banana

5.Replacing String Content

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

65 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

6.Converting to Upper and Lower Case

A string is converted to upper case with toUpperCase():

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

7.The concat() Method


concat() joins two or more strings:

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());

9.Extracting String Characters


There are 3 methods for extracting string characters:
charAt(position)
charCodeAt(position)
The charAt() Method
The charAt() method returns the character at a specified index (position) in a string:
Example
var str = "HELLO WORLD";

66 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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

JavaScript - Errors & Exceptions Handling

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

Runtime errors, also called exceptions, occur during execution (after


compilation/interpretation).

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 try...catch...finally Statement

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.

67 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

You can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.

Here is the try...catch...finally block syntax −

<script type = "text/javascript">

try

// Code to run

catch ( e )

// Code to run if an exception occurs

finally

// Code that is always executed regardless of

// an exception occurring

</script>

68 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

JavaScript Validation
Data validation is the process of ensuring that user input is clean, correct, and useful.

Typical validation tasks are:

 has the user filled in all required fields?


 has the user entered a valid date?
 has the user entered text in a numeric field?

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.

1.Required field Validation

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 == "")

alert("Name must be filled out");

return false;

The function can be called when the form is submitted:

69 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

2.Numeric Field Validation : Is used to check aan input is number

Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<script>

function validate()

var num= document.forms["myForm"]["num"]..value;

if (isNaN(num))

document.getElementById("numloc").innerHTML="Enter Numeric value only";

return false;

3.Format Validation

It evaluate the input and check it is in correct format or not

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)

alert("Password must be at least 6 characters long.");

return false;

70 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

4.Compare Validation: It Compare values from two fields

var pwd=document.myform.password.value;

var pwd1=document.myform.password.value;

if(pwd!=pwd1)

alert("Password does not match”);

return false;

5.Email validation

We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

 email id must contain the @ and . character


 There must be at least one character before and after the @.
 There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

<script>

function validateemail()

var x=document.myform.email.value;

var atposition=x.indexOf("@");

var dotposition=x.lastIndexOf(".");

71 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)

alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n


dotposition:"+dotposition);

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.

Cookies are a plain text data record of 5 variable-length fields −

Expires − The date the cookie will expire. If this is blank, the cookie will expire when the visitor
quits the browser.

Domain − The domain name of your site.

72 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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

The simplest example to set a cookie is:

document.cookie = 'foo=bar'

SET A COOKIE EXPIRATION DATE

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)

document.cookie = 'foo=bar; expires=Mon, 26 Mar 2018 17:04:05 UTC'

SET A COOKIE PATH

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:

document.cookie = 'foo=bar; path="/dashboard"'

DELETE A COOKIE

To delete a cookie, unset its value and pass a date in the past:

document.cookie = 'foo=; expires=Thu, 01 Jan 1970 00:00:00 UTC;'

73 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

MODULE IV
Cascading Style Sheet

74 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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.

You can put CSS Style Rule Syntax as follows −


selector
{
property: value
}

75 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

Example − You can define a table border as follows −


Table
{
border :1px solid #C00;
}

Embedding CSS with HTML


1.Using <style> tag
 You can put your CSS rules into an HTML document using the <style> element.
 This tag is placed inside the <head>...</head> tags. Rules defined using this syntax will
be applied to all the elements available in the document.
Live Demo Live Demo
<html>
<head>
<style type = "text/css" media = "all">
Body
{
background-color: red;
}
h1
{
color: maroon;
margin-left: 40px;
}
</style>
</head>

<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>

</html>

2.Inline CSS - using style Attribute


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 −
<element style = "...style rules....">

Following is the example of inline CSS based on the above syntax −


Live Demo

76 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

<html>
<head>
</head>

<body>
<h1 style = "color:#36C;">
This is inline CSS
</h1>
</body>
</html>

3.External CSS - The <link> Element


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.

Here is the generic syntax of including external CSS file −


<head>
<link type = "text/css" href = "..." media = "..." />
</head>

Extensible Markup Language-XML


XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML).

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.

77 Muslim Association College of Arts and Science


Web Programming Notes B .Sc CS

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 be used to store and arrange the data

 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 −

<?xml version = "1.0"?>


<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

78 Muslim Association College of Arts and Science

You might also like