0% found this document useful (0 votes)
257 views227 pages

Dmc6010 Web Design

This document provides a syllabus for a course on web programming. It outlines 5 units that will be covered: 1. Introduction to the World Wide Web, including its history, architecture, protocols, and principles of web design. 2. User interface design using HTML, CSS, and responsive design. 3. Advanced CSS techniques like positioning, flexbox, CSS frameworks and animations. 4. JavaScript for interactivity, DOM manipulation, events, and libraries like jQuery. 5. Server-side programming using PHP for forms, files, databases and more. The syllabus details the topics, objectives and schedule for each of the 5 units that comprise the web programming course.

Uploaded by

harish
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 (0 votes)
257 views227 pages

Dmc6010 Web Design

This document provides a syllabus for a course on web programming. It outlines 5 units that will be covered: 1. Introduction to the World Wide Web, including its history, architecture, protocols, and principles of web design. 2. User interface design using HTML, CSS, and responsive design. 3. Advanced CSS techniques like positioning, flexbox, CSS frameworks and animations. 4. JavaScript for interactivity, DOM manipulation, events, and libraries like jQuery. 5. Server-side programming using PHP for forms, files, databases and more. The syllabus details the topics, objectives and schedule for each of the 5 units that comprise the web programming course.

Uploaded by

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

DMC 6010

MASTER OF
COMPUTER APPLICATIONS

WEB DESIGN

CENTRE FOR DISTANCE EDUCATION


ANNA UNIVERSITY
CHENNAI – 600 025
1
WEB PROGRAMMING
SYLLABUS

UNIT-I INTRODUCTION TO WWW


Understanding the working of Internet-Web Application Architecture-Brief history of Internet-Web
Standards - W3C-Technologies involved in Web Development Protocols-Basic Principles involved in
developing a Website-Five Golden Rules of Web Designing.
UNIT-II UI DESIGN
HTML Documents-Understanding Markup Languages-Structure of HTML Documents-Markup Tags
Basic Markup Tags-Working with Text-Working with Images-Hyperlinks Images-Tables-List-SVG
Advanced HTML- Iframes-HTML5 Video and Audio tags
Cascading Style Sheet: Need for CSS Importance of separating document structuring and Styling-Basic
CSS selectors and properties-CSS properties for text (Color, font, weight, align etc.) and working with
Colors-Selecting with classes, IDs, tags-CSS Specificity-Ways of linking CSS to HTML-CSS Pseudo
selectors- Understanding the box Model-Margins, padding and Border-Inline and block elements -
Structuring pages using Semantic Tags
UNIT-III WEB PAGE LAYOUTS WITH CSS3
Positioning with CSS - Positions, Floats, z-Index-Layouts with Flexbox -Responsive web design.
with media queries-Advanced CSS Effects - Gradients, opacity, box-shadow-CSS3 Animations
Transforms and Transitions-CSS Frameworks – Bootstrap
UNIT-IV JAVA SCRIPT
Basic JavaScript Syntax-JavaScript Objects and JSON-Understanding the DOM-JavaScript
Events and Input Validation-Modifying CSS of elements using JavaScript-JavaScript Local
Storage and Session Storage-Cross domain data transfer with AJAX-Using JQuery to add
interactivity-JQuery Selectors-JQuery Events-Modifying CSS with JQuery -Adding and
removing elements with JQuery-AJAX with JQuery-Animations with JQuery (hide, show,
animate, fade methods. Slide Method)

UNIT-V SERVER-SIDE PROGRAMMING WITH PHP


PHP basic syntax-PHIP Variables and basic data Structures-Using PHP to manage form. Submissions-
File Handing Cookies and Sessions with PHP-Working with WVAMP and PHPMYADMIN-
Establishing connectivity with MySQL using PHP

2
WEB PROGRAMMING
SCHEME OF LESSONS
UNIT-I
S.NO TOPICS PAGE NUMBER
1.1 World Wide Web (Www) 6
1.2 Understanding Internet 6
1.3 Communicating On Internet 7
1.4 WWW Architecture 7
1.5 Web Server 9
1.6 Web Browsers 10
1.7 History of Internet 11
1.8 Web Design and Applications 11
1.9 Protocols 12
1.10 Designing A Web Page 20
1.11 Summary 23
UNIT-II
2.1 Introduction to HTML 25
2.2 26
Basic markup tags
2.3 52
SVG Element
2.4 56
Cascading Style Sheets
2.5 60
The CSS Box Model
2.6 61
CSS Margin
2.7 62
Padding
28. 63
Class Selectors
29 64
Inline and Block Elements
2.10 65
Structuring pages using Semantic Tags
UNIT-III
3.1 Cascading Style Sheet-Definition 73
3.2 Classification of CSS 73
3.3 CSS Structure 77
3.4 CSS Positioning 77
3.5 CSS floats and z-index 79
3.6 Layouts with Flexbox 84
3.7 Responsive web Design with media queries 89
3.8 Advanced CSS Effects 95
3.9 Gradients opacity, box shadow 97
3.10 CSS Animations 98
3.11 CSS Framework 103
3.12 Bootstrap 104
UNIT-IV
4.1 108
Basics of JavaScript
4.2 118
JavaScript Objects
3
4.3 133
JSON
4.4 139
Understanding the DOM
4.5 140
JavaScript Events and Input Validation.
4.6 148
Modifying CSS Elements using JavaScript.
4.7 151
JavaScript Local Storage
4.8 152
Ajax.
4.9 158
Jquery Selectors
4.10 159
Adding and Removing Elements with Jquery.
4.11 162
Ajax with Jquery.
4.12 Animation with Jquery 165
V-UNIT
5.1 An PHP Basics 169
5.2 PHP Variables 171
5.3 PHP Program Control 171
5.4 PHP – Arrays 175
5.5 PHP User Defined Functions 178
5.6 File Handling with PHP 179
5.7 Cookies 184

5.8 Working with WAMP and PHPADMIN 186

5.9 Establishing with MYSQL using PHP 196

Programs 202

Model Question Paper 226

4
UNIT-I
CONTENTS
Learning Objectives
Learning Outcomes
Overview

1.1 World Wide Web (Www)


1.2 Understanding Internet
1.3 Communicating On Internet
1.4 WWW Architecture
1.5 Web Server
1.6 Web Browsers
1.7 History of Internet
1.8 W3C standards AND Technologies in web development Protocols
1.9 Protocols
1.10 Designing a Web Page
1.11 Summary
Keywords
Self-Assessment Questions
Further Readings

LEARNING OBJECTIVES

After studying this lesson, you should be able to:


 Learn about the World Wide Web
 Know the principles of developing websites
 Understand the Golden rules of web designing

LEARNING OUTCOMES

Upon completion of the lesson, students are able to demonstrate a good understanding
of:
 concept of World Wide Web (WWW) and how to use linking
 determine dynamic updates of web pages
 Basic principles involved in developing a web site
 Concept of protocol
 concept of web Designing

OVERVIEW
In this lesson, you will learn about the World Wide Web (Web). World Wide Web is a network of
information resources. The World Wide Web is a system of interlinked hypertext documents that
are accessed via the Internet. With a web browser, one can view web pages that may contain text,
images, videos, and other multimedia and navigate between them via hyperlinks. To study the

5
dynamic updates of web pages and concept of protocols and steps to create a web Dessigning.

1.1 WORLD WIDE WEB (WWW)


The World Wide Web (abbreviated as WWW or W3) commonly known as the web) is a system of
interlinked hypertext documents accessed via the Internet. With a web browser, one can view web
pages that may contain text, images, videos, and other multimedia and navigate between them via
hyperlinks.

The World Wide Web (abbreviated WWW or the Web) is an information space where documents
and other web resources are identified by Uniform Resource Locators (URLs), interlinked by
hypertext links, and can be accessed via the Internet. English scientist Tim Berners invented the
World Wide Web in 1989. He wrote the first web browser computer program in 1990 while
employed at CERN in Switzerland. The Web browser was released outside CERN in 1991, first to
other research institutions starting in January 1991 and to the public on the Internet in August
1991.

The World Wide Web has been central to the development of the Information Age and is
the primary tool billions of people use to interact on the Internet. Web pages are primarily
text documents formatted and annotated with Hypertext Markup Language (HTML). In
addition to formatted text, web pages may contain images, video, audio, and software
components that are rendered in the user's web browser as coherent pages of multimedia
content.

Embedded hyperlinks permit users to navigate between web pages. Multiple web pages
with a common theme, a common domain name, or both, make up a website. Website
content can largely be provided by the publisher, or interactively where users contribute
content, or the content depends upon the users or their actions. Websites may be mostly
informative, primarily for entertainment, or largely for commercial, governmental, or non-
governmental organizational purposes
1.2 UNDERSTANDING INTERNET

Understanding Internet Basics


You can program for the Web, using your skills as a Visual Basic programmer, no matter what
your level of experience with Internet technology. If you are new to the Internet or unfamiliar with
its technology, Visual Basic allows you to produce functional applications quickly and easily. If
you are more experienced with Internet technology, you can work at a more advanced level. From
one perspective, Internet technology simply provides another area for your development efforts.
When you deploy Internet applications on the Web, you may go about it differently —
incorporating HTML pages with your Visual Basic code, providing security features, and so on —
but you're still calling methods, setting properties, and handling events. In this way, all your
knowledge as a Visual Basic developer can be carried into the Internet arena.
From another perspective, applying Internet technology enables you to extend your development
skills in exciting new ways. For example, writing Visual Basic code that manipulates HTML
pages allows you to decrease deployment costs, reduce client maintenance problems, and reach the
broad audience of the Internet.

The Internet and the World Wide Web are not the same. The Internet is a global
system of interconnected computer networks. In contrast,the web is one of the services that
run on the Internet. It is a collection of text documents and other resources, linked by
hyperlinks and URLs, usuallyaccessed by web browsers from web servers.

6
1.3 Communicating on Internet
Communication is the most popular use of the Internet, with email topping the list of all the technologies
used. Some of the types of communication technologies used also include email discussion groups, Usenet
news, chat groups, and IRC. These are unique to networked computer environments and have come into
wide popularity because of the Internet. Other technologies, including video and audio conferencing and
Internet telephony, are also available on the Internet. They require more multimedia capabilities of
computer systems and are more taxing of network resources than the others. They also are adaptations of
other technologies to the Internet.
Most of the technologies that are unique to the Internet require communication to be done in
text—letters with some symbols and punctuation.

Notes Communicating effectively involves taking the time, except in


informal communications, to use correct grammar, spelling, and punctuation
and writing an appropriate message. When replying to a message include the
pertinent parts of the message and use an appropriate and interesting subject
header in any case.
1.4 WWW ARCHITECTURE
The www is a distributed client/server service, in which a client using a browser can access a
service using a server. However, the service provided is distributed over many locations called
sites.
Each sites holds one or more documents, referred to as web pages. Each web page can contain a
link to other pages in the same site or at other sites. The pages can be retrieved and viewed by
browsers.
The web is a two-tiered architecture. A web browser displays information content,
and a web server that transfers information to the client. A web browser runs on the client, Internet
Explorer, Netscape, A web server runs on the server, IIS, Apache, the client, and server
communicate using the http protocol

Request for
Web Page Request for
Network Web page

Web page
HTML file Web Page
HTML File

Web Browser (Uses’s Web Server


Computer or Client

Fig. 1.1 Web Two tired Architecture

The client needs to see some information that it knows belongs to site A. It sends a request
through its browser, a program that is designed to fetch web documents. The request, among other
information, includes the address of the site and the web page, called the URL (Uniform Resource
Locator).

7
The server at site A finds the document and sends it to the client. When the user views the
document, the user finds some references to other documents, including a web page at site B. The
reference has the URL for the new site. The user is also interested in seeing this document. The
client sends another request to the new site, and the new page is retrieved.

1.4.1 Client

➤ A variety of vendors offer commercial browsers that interpret and display a web document, and
all use nearly the same architecture. Each browser usually consists of three parts:

i) A Controller,

ii) Client Protocol, and iii) Interpreters.

The controller receives input from the keyboard or the mouse and

uses the client programs to access the document. After the document has been accessed, the
controller uses one of the interpreters to display the document on the screen. >The client protocol
can be one of the protocols such as FTP. The interpreter can be HTML, Java, or JavaScript,
depending on the type of document as shown in figure:
BROWSER

HTML
CONTROLLER

JavaScript

HTTP FTP SMTP Java


TELNET

Fig. 1.2 Interpreter


1.4.2 Server

The web page is stored at the server. Each time a client request arrives, the corresponding
document is sent to the client. To improve efficiency, servers normally store requested files in a
cache in memory; memory is faster to access than disk. > A server can also become more efficient
through multithreading or multiprocessing. In this case, a server can answer more than one request
at a time. Uniform Resource Locator (URL)

A client that wants to access a web page needs the address. To facilitate the access of documents
distributed throughout the world, HTTP uses locators.

> The Uniform Resource Locator (URL) is a standard for specifying any kind of information on
the internet. The URL defines four things - protocol, host computer, port, and path as shown in
figure

Protocol :// Host : Port / Path

Fig. 1.3 URL


8
The protocol is the client/server program used to retrieve the document. Many different protocols
can retrieve a document; among them are FTP or HTTP. The most common today is HTTP.

The host is the computer on which the information is located, although the name of the computer
can be as alias. Web pages are usually stored in computers, and computers are given alias names
that usually begin with the characters "WWW". This is not mandatory, however, as the host can be
any name given to the computer that hosts the web page. The URL can optionally contain the port
number of the server. If the port is included, it is inserted between the host and the path, and it is
separated from the host by a colon.

Path is the pathname of the file where the information is located the path can contain slashes that
separate the directories from the sub-directories and files.

1.4.3 Cookies

The World Wide Web was originally designed as a stateless entity. A client sends a request; a
server responds. Their relationship is over. The original design of WWW is retrieving publicly
available documents. Today the web has other functions; some are:

1) Some websites need to allow access to registered clients only.


2) Websites are being used as electronic stores that allow users to browse through the store, select
wanted items, put them in an electronic cart, and pay at the end with a credit card.
3) Some websites are used as portals; the user selects the web pages that the user wants to see.
4) Some websites are just advertising. For these purposes, the cookie mechanism was devised.

1.5 web server

A web server is a computer system that processes requests via HTTP, the basic network protocol used to
distribute information on the World Wide Web. The term can refer to the entire system, or specifically to the
software that accepts and supervises the HTTP requests.

Overview The primary function of a web server is to store, process and deliver web pages to clients. The
communication between client and server takes place using the Hypertext Transfer Protocol (HTTP). Pages
delivered are most frequently HTML documents, which may include images, style sheets and scripts in
addition to text content.

Fig. 1.4 Server


Multiple web servers may be used for a high traffic website, here Dell servers are installed together being
used for the Wikimedia Foundation

A user agent, commonly a web browser or web crawler, initiates communication by making a request for a
specific resource using HTTP and the server responds with the content of that resource or an error message if
unable to do so. The resource is typically a real file on the server's secondary storage, but this is not
necessarily the case and depends on how the web server is implemented.
9
While the primary function is to serve content, a full implementation of HTTP also includes ways of
receiving content from clients. This feature is used for submitting web forms, including uploading of files.

Many generic web servers also support server-side scripting using Active Server Pages (ASP), PHP, or other
scripting languages. This means that the behavior of the web server can be scripted in separate files, while the
actual server software remains unchanged. Usually, this function is used to generate HTML documents
dynamically ("on-the-fly") as opposed to returning static documents. The former is primarily used for
retrieving or modifying information from databases. The latter is typically much faster and more easily
cached but cannot deliver dynamic content.

Web servers are not only used for serving the World Wide Web. They can also be found embedded in
devices such as printers, routers, webcams and serving only a local network. The web server may then be
used as a part of a system for monitoring or administering the device in question. This usually means that no
additional software must be installed on the client computer, since only a web browser is required (which
now is included with most operating systems).

1.6 WEB BROWSERS

To access the World Wide Web, you use what is called a Web browser (already discussed in the previous
chapter). Browsers are sometimes also called Web clients since they get information from a server. When
you start a WWW browser or follow a hyperlink, the browser (acting like a client) sends a request to a site on
the Internet. That site (acting like a server) returns a file which

the browser then must display. For you to see or hear what's in the file, the browser should be capable of
interrupting its contents. This differs depending on the type of file, text, graphics and/or images that may be
displayed. If the file is written using Hypertext Markup Language (HTML), the browser interprets the file so
that graphics and images are displayed along with the text.
1.6.1 Basic Features of Browsers

Before we get involved in all the details, let is discuss some important browser features.
1.The Web browser should be able to look at the Web pages throughout the Internet or to connect to various
sites to access information, explore resources, and have fun.
2.The Web browser must enable you to follow the hyperlinks on a Web page and to type in a URL for it to
follow.
3.Another feature of browser is to have several other commands readily available through menus, icons, and
buttons.
4.Your browser ought to include an easy way to get on-line help as well as built-in links to other resources on
the Web that can give you help or answers to your questions.
5.You will want a way to save links to the sites you have visited on the WWW so that you can get back to
them during other sessions. Web browsers take care of those in two ways, through a history list, which keeps
a record of some of the Web pages you've come across in the current session, and a bookmark list, which you
use to keep a list of WWW pages you want to access any time you use your browser. The name of the site
and its URL are kept in these lists. The bookmark list is particularly important, and the browser will contain
tools to manage and arrange it.
6.One of the main features of a browser is to search the information on the current page as well as search the
WWW itself.
7.Browsers give you the facility to save a Web page in a file on your computer, print a Web page on your
computer, and send the contents of a Web page by e-mail to others on the Internet.
8.Few Web browsers (like Netscape Communicator) are complete Internet package, means they come with
components like e-mail client, newsgroup client, an HTML composer, telnet client, ftp client, etc.
9.Web browser should be able to handle text, images of the World Wide Web, as well as the hyperlinks to
10
digital video, or other types of information.
10.To take advantage of some of the most exciting things on the World Wide Web, your browser needs to
properly display and handle Web pages that contain animated or interactive items. Netscape Navigator can
incorporate these features through its ability to interpret programs written in Java and Java Script.

1.7 History of Internet

This marvelous tool has quite a history that holds its roots in the cold war scenario. A need was realized to
connect the top universities of the United States so that they can share all the research data without having
too much of a time lag. This attempt was a result of Advanced Research Projects Agency (ARPA) which was
formed at the end of 1950s just after the Russians had climbed the space era with the launch of Sputnik. After
the ARPA got success in 1969, it didn‘t ‗t takes the experts long to understand that how much potential can
this interconnection tool have. In 1971 Ray Tomlinson made a system to send electronic mail. This was a big
step in the making as this opened gateway for remote computer accessing i.e., Telnet.

During all this time, rigorous paperwork was being done in all the elite research institutions. From giving
every computer an address to setting out the rules, everything was getting penned down. 1973 saw the
preparations for the vital TCP/IP and Ethernet services. At the end of 1970s, Usenet groups had surfaced up.
By the time the 80s had started, IBM came up with its PC based on Intel 8088 processor which was widely
used by students and universities for it solved the purpose of easy computing. By 1982, the Defense Agencies
made the TCP/IP compulsory and the term ―internet‖ was coined. The domain name services arrived in the
year 1984 which is also the time around which various internet based marked their debut. A worm, or a rust
the computers, attacked in 1988 and disabled over 10% of the computer systems all over the world. While
most of the researchers regarded it as an opportunity to enhance computing as it was still in its juvenile
phase, quite several computer companies became interested in dissecting the cores of the malware which
resulted to the formation Computer Emergency Rescue Team (CERT). Soon after the world got over with the
computer worm, World Wide Web came into existence. Discovered by Tim Berners-Lee, World Wide Web
was seen as a service to connect documents in websites using hyperlinks. So, the history can be summarized
as

 It was originated in 1969 at ARPANET (Advanced research project Agency) of DoD (Department of
Defense), USA
 Its prime purpose was to connect among various bodies of US government
 Initially there were only four nodes (Hosts)
 In 1972, ARPANET was spread across the globe with 23 nodes at different parts of the world
 Then all the other organizations in respective countries joined to this network to send and receive data
among other countries
 Thereby internet has got populated with number of networks, thus became a tech giant
 Around 1990s, Tim Berners Lee and O-Reilly had developed WWW and other internet
communication protocols

1.8 W3C standards AND Technologies in web development


W3C standards define an Open Web Platform for application development that has the unprecedented
potential to enable developers to build rich interactive experiences, powered by vast data stores, that are
available on any device. Although the boundaries of the platform continue to evolve, industry leaders
speak nearly in unison about how HTML5 will be the cornerstone for this platform. But the full strength
of the platform relies on many more technologies that W3C and its partners are creating, including CSS,
SVG, WOFF, the Semantic Web stack, XML, and a variety of APIs.

W3C develops these technical specifications and guidelines through a process designed to maximize
consensus about the content of a technical report, to ensure high technical and editorial quality, and to
11
earn endorsement by W3C and the broader community.

If you are learning about Web technology, you may wish to start with the introduction below, and follow
links for greater detail.

1.8.1 WEB DESIGN AND APPLICATIONS


Web Design and Applications involve the standards for building and Rendering Web pages, including
HTML, CSS, SVG, device APIs, and other technologies for Web Applications (―Web Apps‖). This
section also includes information on how to make pages accessible to people with disabilities (WCAG),
to internationalize them, and make them work on mobile devices.
Web Design and Applications
Web Design and Applications involve the standards for building and Rendering Web pages, including
HTML, CSS, SVG, Ajax, and other technologies for Web Applications (―Web Apps‖). This section also
includes information on how to make pages accessible to people with disabilities (WCAG), to
internationalize them, and make them work on mobile devices.
Web of Devices
W3C is focusing on technologies to enable Web access anywhere, anytime, using any device. This
includes Web access from mobile phones and other mobile devices as well as use of Web technology in
consumer electronics, printers, interactive television, and even automobiles.
Web Architecture
Web Architecture focuses on the foundation technologies and principles which sustain the Web,
including URIs and HTTP.
Semantic Web
In addition to the classic ―Web of documents‖ W3C is helping to build a technology stack to support a
―Web of data,‖ the sort of data you find in databases. The ultimate goal of the Web of data is to enable
computers to do more useful work and to develop systems that can support trusted interactions over the
network. The term ―Semantic Web‖ refers to W3C‘s vision of the Web of linked data. Semantic Web
technologies enable people to create data stores on the Web, build vocabularies, and write rules for
handling data. Linked data are empowered by technologies such as RDF, SPARQL, OWL, and SKOS.
XML Technology
XML Technologies including XML, XML Namespaces, XML Schema, XSLT, Efficient XML
Interchange (EXI), and other related standards.
Web of Services
Web of Services refers to message-based design frequently found on the Web and in enterprise software.
The Web of Services is based on technologies such as HTTP, XML, SOAP, WSDL, SPARQL, and
others.

Browsers and Authoring Tools


The web's usefulness and growth depend on its universality. We should be able to publish regardless of
the software we use, the computer we have, the language we speak, whether we are wired or wireless,
regardless of our sensory or interaction modes. We should be able to access the web from any kind of
hardware that can connect to the Internet – stationary or mobile, small, or large. W3C facilitates this
listening and blending via international web standards. These standards ensure that all the crazy brilliance
continues to improve a web that is open to us all.

1.9 PROTOCOLS

"The term protocol is used to refer to a well-known set of rules and formats to be used for
communication between processes in order to perform a given task."

A protocol is an agreed way of working also known as 'handshake'. If computers do not use the same
protocol, it becomes impossible for them to understand the data transmitted between them. This is similar
to humans who speak different languages - unless they agree to speak to a common language, they will
not be able to understand each other.

12
Internet protocols include mechanisms for devices to identify and make connections with each other, as
well as formatting rules that specify how data is packaged into messages sent and received.

Some protocols also support message acknowledgement and data compression designed for reliable
and/or high-performance network communication.
For internet and World Wide Web, the following protocols are most widely used.
HTTP 2. SMTP 3. POP3 4. File Transfer Protocol

1.9.1 HTTP

 HTTP stands for Hypertext Transfer Protocol.


 It is a protocol used to access the data on the World Wide Web (www).
 The HTTP protocol can be used to transfer the data in the form of plain text, hypertext, audio,
video, and so on.
 This protocol is known as Hypertext Transfer Protocol because of its efficiency that allows us to
use in a hypertext environment where there are rapid jumps from one document to another
document.
 HTTP is like the FTP as it also transfers the files from one host to another host. But HTTP is
simpler than FTP as HTTP uses only one connection, i.e., no control connection to transfer the
files.
 HTTP is used to carry the data in the form of MIME-like format.
 HTTP is similar to SMTP as the data is transferred between client and server. The HTTP differs
from the SMTP in the way the messages are sent from the client to the server and from server to
the client. SMTP messages are stored and forwarded while HTTP messages are delivered
immediately.
Features of HTTP:
o Connectionless protocol: HTTP is a connectionless protocol. HTTP client initiates a request and
waits for a response from the server. When the server receives the request, the server processes the
request and sends back the response to the HTTP client after which the client disconnects the
connection. The connection between client and server exists only during the current request and
response time only.
o Media independent: HTTP protocol is a media independent as data can be sent as long as both the
client and server know how to handle the data content. It is required for both the client and server to
specify the content type in MIME-type header.
o Stateless: HTTP is a stateless protocol as both the client and server know each other only during
the current request. Due to this nature of the protocol, both the client and server do not retain the
information between various requests of the web pages.
HTTP messages are of two types:
 Request
 Response.
Request Message:
Structure of the request:
 start line
 header field(s)
 blank line
 optional body
13
Start line contain three space-separated parts:
1. HTTP request method
2. Request-URI (Uniform Resource Identifier)
3. HTTP version Example:
GET / HTTP/1.1 Common request
methods: GET

POST
HEAD
Used if link is clicked or address typed in browser No body in request with GET method Used when submit button
is clicked on a form information contained in body of request

Requests that only header fields (no body) be returned in the response HTTP version
We will cover 1.1, in which version part of start line must be exactly as shown
Header field structure: Syntax
field name: field value
Field name is not case sensitive
Field value may continue multiple lines by starting continuation lines with white space
Field values may contain MIME types, quality values, and wildcard characters (*‘s).
Example: text/html, image/jpeg
Common header fields:
 Host: host name from URL (required)
 User-Agent: type of browser sending request
 Accept: MIME types of acceptable documents
 Connection: value close tells server to close connection after single request/response
 Content-Type: MIME type of (POST) body, normally application/x-www-form- URL
encoded
 Content-Length: bytes in body
Referrer: URL of document containing link that supplied URI for this HTTP request
Example
GET /hello.htm HTTP/1.1 (This is Request-Line sent by the client)
HTTP/1.1 200 OK (This is Status-Line sent by the server) User-Agent: curl/7.16.3
libcurl/7.16.3 OpenSSL/0.9.7l zlib/1.2.3
Host: www.example.com
Accept-Language: en, mi
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
ETag: "34aa387-d-1568eb00"
Accept-Ranges: bytes
Content-Length: 51
Vary: Accept-Encoding
Content-Type: text/plain
Response Message:
Structure of the response:

14
 status line
 header field(s)
 blank line
 optional body
Status line
Example: HTTP/1.1 200 OK Three space-
separated parts:
 HTTP version
 status code
 reason phrase (intended for human use)
Status code: a three-digit number First digit
is class of the status code:
 1=Informational
 2=Success
 3=Redirection (alternate URL is supplied)
 4=Client Error
 5=Server Error
Other two digits provide additional information
Common header fields:
 Connection, Content-Type, Content-Length
 Date: date and time at which response was generated (required)
 Location: alternate URI if status is redirection
 Last-Modified: date and time the requested resource was last modified on the server
 Expires: date and time after which the client‘s copy of the resource will be out-of-date
 ETag: a unique identifier for this version of the requested resource (changes if resource changes)
Example
HTTP/1.1 200 OK
Date: Sun, 20 Feb 2011 03:49:19 GMT
Server: Apache
Set-Cookie: BBC-UID=d4fd96e01cf7083; expires=Mon, 20-Feb-12 07:49:32 GMT;
path=/;domain=bbc.co.uk;
Cache-Control: max-age=0
Expires: Sun, 20 Feb 2011 03:49:19 GMT Keep-
Alive: timeout=10, max=796 Transfer-Encoding:
chunked
Content-Type: text/html
Connection: keep-alive

1.9.2 SMTP
 SMTP stands for Simple Mail Transfer Protocol.
 SMTP is a set of communication guidelines that allow software to transmit an electronic mail
over the internet is called Simple Mail Transfer Protocol.
 It is a program used for sending messages to other computer users based on e-mail addresses.
 It provides a mail exchange between users on the same or different computers, and it also
supports:
o It can send a single message to one or more recipients.

15
o Sending message can include text, voice, video, or graphics.
o It can also send the messages on networks outside the internet.
 The main purpose of SMTP is used to set up communication rules between servers. The servers
have a way of identifying themselves and announcing what kind of communication they are
trying to perform. They also have a way of handling the errors such as incorrect email address.
For example, if the recipient address is wrong, then receiving server reply with an error message
of some kind.
Working of SMTP
1. Composition of Mail: A user sends an e-mail by composing an electronic mail message using a
Mail User Agent (MUA). Mail User Agent is a program which is used to send and receive mail.
The message contains two parts: body and header. The body is the main part of the message while
the header includes information such as the sender and recipient address. The header also includes
descriptive information such as the subject of the message. In this case, the message body is like a
letter and header is like an envelope that contains the recipient's address.
2. Submission of Mail: After composing an email, the mail client then submits the completed e-mail
to the SMTP server by using SMTP on TCP port 25.
3. Delivery of Mail: E-mail addresses contain two parts: username of the recipient and domain name.
For example, [email protected], where "Vivek" is the username of the recipient and
"gmail.com" is the domain name. If the domain name of the
recipient's email address is different from the sender's domain name, then MSA will send the mail to
the Mail Transfer Agent (MTA). To relay the email, the MTA will find the target domain. It checks the MX
record from Domain Name System to obtain the target domain. The MX record contains the domain name
and IP address of the recipient's domain. Once the record is located, MTA connects to the exchange server to
relay the message.
4. Receipt and Processing of Mail: Once the incoming message is received, the exchange server
delivers it to the incoming server (Mail Delivery Agent) which stores the e-mail where it waits for
the user to retrieve it.
5. Access and Retrieval of Mail: The stored email in MDA can be retrieved by using MUA (Mail
User Agent). MUA can be accessed by using login and password.

1.9.3 Transmission Control Protocol (TCP)


TCP (Transmission Control Protocol) is a standard that defines how to establish and maintain a network
conversation through which application programs can exchange data.
TCP is a connection-oriented protocol, which means a connection is established and maintained until the
application programs at each end have finished exchanging messages.
It determines how to break application data into packets that networks can deliver sends packets to and
accepts packets from the network layer, manages flow control
TCP is used for organizing data in a way that ensures the secure transmission between the server and
client. It guarantees the integrity of data sent over the network, regardless of the amount.
TCP is important because it establishes the rules and standard procedures for the way information is
communicated over the internet. It is the foundation for the internet as it exists today and ensures that data
transmission is carried out uniformly, regardless of the location, hardware or software involved.
TCP exists in the transport layer with other protocols such as UDP. Protocols in this layer ensure the error
free transmission of data to the source
 TCP offers:
o Stream Data Transfer.
o Reliability.
o Efficient Flow Control

16
o Full-duplex operation.
o Multiplexing.
TCP offers following services to the processes at the application layer:
 Stream Delivery Service
 Sending and Receiving Buffers
 Bytes and Segments
 Full Duplex Service
 Connection Oriented Service

1.9.4 Internet Protocol (IP)


The Internet Protocol (IP) is a protocol, or set of rules, for routing and addressing packets of data so that
they can travel across networks and arrive at the correct destination.
Internet Protocol is connectionless and unreliable protocol. It ensures no guarantee of successfully
transmission of data.
To make it reliable, it must be paired with reliable protocol such as TCP at the transport layer.
The main purpose and task of IP is the delivery of datagrams from the source host (source computer) to the
destination host (receiving computer) based on their addresses. To achieve this, IP includes methods and
structures for putting tags (address information, which is part of metadata) within datagrams The process of
putting these tags on datagrams is called encapsulation
Internet protocol transmits the data in form of a datagram as shown in the following diagram:
4 8 16 32bits

VER HLEN D.S.type of service Total length of 16 bits

Identification of 16 bits Flags Fragmentation


3 bits Offset(13 bits)

Timde to live Protocol Header checksum(16 bits)

Source of IP address

Destination IP address

Option+padding

Fig. 1.5 Datagram

Points to remember:
 The length of datagram is variable.
 The Datagram is divided into two parts: header and data.
 The length of header is 20 to 60 bytes.
 The header contains information for routing and delivery of the packet.
Limitations of IP:
 No guarantee of packet delivery (packets can be dropped)
 Communication is one-way (source to destination)

17
1.9.5 User Datagram Protocol (UDP)
The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol available of the
TCP/IP protocol suite. It involves minimum amount of communication mechanism. UDP is said to be an
unreliable transport protocol, but it uses IP services which provides best effort delivery mechanism.
In UDP, the receiver does not generate an acknowledgement of packet received and in turn, the sender
does not wait for any acknowledgement of packet sent. This shortcoming makes this protocol unreliable
as well as easier on processing.

Features
 UDP is used when acknowledgement of data does not hold any significance.
 UDP is good protocol for data flowing in one direction.
 UDP is simple and suitable for query-based communications.
 UDP is not connection oriented.
UDP does not provide congestion control mechanism.
 UDP does not guarantee ordered delivery of data.
 UDP is stateless.
 UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.
UDP Header
0 15 16 31
Source Port Destibation Port
Length Checksum

Fig. 1.6 UDP Header

UDP header is as simple as its function.


UDP header contains four main parameters:
 Source Port - This 16-bit information is used to identify the source port of the packet.
 Destination Port - This 16-bit information, is used identify application level service on destination
machine.
 Length - Length field specifies the entire length of UDP packet (including header). It is 16-bits
field and minimum value is 8-byte, i.e., the size of UDP header itself.
 Checksum - This field stores the checksum value generated by the sender before sending. IPv4 has
this field as optional so when checksum field does not contain any value it is made 0 and all its
bits are set to zero.
UDP application
Here are few applications where UDP is used to transmit data:
 Domain Name Services
 Simple Network Management Protocol
 Trivial File Transfer Protocol
 Routing Information Protocol
 Kerberos

18
1.9.6 File Transfer Protocol (FTP)
 FTP stands for File transfer protocol.
 FTP is a standard internet protocol provided by TCP/IP used for transmitting the files from one host
to another.
 It is mainly used for transferring the web page files from their creator to the computer that acts as a
server for other computers on the internet.
 It is also used for downloading the files to computer from other servers.
 It provides the sharing of files.
 It is used to encourage the use of remote computers.
 It transfers the data more reliably and efficiently.

User Interface Control connection

Control Processs Control Process

TCP/IP
Storage Data transfer Process Data transfer Storage
process

Data connection

Fig. 1.7 FTP


The above figure shows the basic model of the FTP. The FTP client has three components: the user
interface, control process, and data transfer process. The server has two components: the server control
process and the server data transfer process.
There are two types of connections in FTP
 Control Connection: The control connection uses very simple rules for communication.
Through control connection, we can transfer a line of command or line of response at a time.
The control connection is made between the control processes. The control connection remains
connected during the entire interactive FTP session.
 Data Connection: The Data Connection uses very complex rules as data types may vary. The
data connection is made between data transfer processes. The data connection opens when a
command comes for transferring the files and closes when the file is transferred.
FTP Clients
 FTP client is a program that implements a file transfer protocol which allows you to transfer files
between two hosts on the internet.
 It allows a user to connect to a remote host and upload or download the files.
 It has a set of commands that we can use to connect to a host, transfer the files between you and your
host and close the connection.
 The FTP program is also available as a built-in component in a Web browser. This GUI based FTP
client makes the file transfer very easy and does not require to remember the FTP commands.
Advantages of FTP:
 Speed: One of the biggest advantages of FTP is speed. The FTP is one of the fastest ways to
transfer the files from one computer to another computer.
 Efficient: It is more efficient as we do not need to complete all the operations to get the entire
file.
 Security: To access the FTP server, we need to login with the username and password.
19
Therefore, we can say that FTP is more secure.
 Back & forth movement: FTP allows us to transfer the files back and forth. Suppose you are a
manager of the company, you send some information to all the employees, and they all send
information back on the same server.
Disadvantages of FTP:
 The standard requirement of the industry is that all the FTP transmissions should be encrypted.
However, not all the FTP providers are equal and not all the providers offer encryption. So, we will
have to look out for the FTP providers that provides encryption.
 FTP serves two operations, i.e., to send and receive large files on a network. However, the size limit
of the file is 2GB that can be sent. It also doesn't allow you to run simultaneous transfers to multiple
receivers.
 Passwords and file contents are sent in clear text that allows unwanted eavesdropping. So, it is quite
possible that attackers can carry out the brute force attack by trying to guess the FTP password.
 It is not compatible with every system.
1.9.7 POP3:
POP3 stands for Post Office Protocol Version3.
POP3 allows user Transfer Agent to contract message transfer agent and allow e-mail to be copied from ISP
to the user. Two situations can be handled by POP3 If both the sender and receiver are online. If sender is
online but receiver is not.

Data Transfer Connection


Steps:
1. POP3 begins when user starts mail reader.
2. Mail reader calls up the ISP and establishes a TCP Connection with MTA at port110
3.POP3 goes through 3 states in sequence after connection establishment
Authorization:
It deals with having user login.
Transaction:
It deals with the user collecting the e-mails and marking them for deletion from the mailbox.
Update:
Actually, causes email to be deleted.
Commands:
USER – Gets the username
PASS- Gets the password of the user.
LIST- Causes the server to list the contents of mailbox, one message per line, giving the length of the
message period (.) terminates the list.
RETR- Used to retrieve the messages
DELE- Used to mark the messages to be deleted.
QUIT- Used to terminate the transaction state and enter update state.

1.10 DESIGNING A WEB PAGE


A website is an address (location) on the World Wide Web that contains your web pages.
Basically, a website is your personal online communications connection to the rest of the
world. It is totally different from any other type of publishing, advertising, or communications
media.

Designing for the web requires the relevant content of a brochure or magazine, the colorful
look of high-quality print, and the attention-grabbing impact of television advertising. Plus, it should offer a
valuable product and/or information, be updated frequently and stay current
with changing technology.
1.10.1 Objectives:
After reading this unit you will be able to understand different aspects of planning a
20
website. Different issues related to website design such as goal setting, target
audience and tips related to better navigation have been covered in detail. Tools and
whereabouts of webpage hosting and working through webpage has also been covered.
1.10.2 Building a case for planning
For a small to medium sized business, initiating a website can be one of the toughest
jobs you'll face. This section is designed to provide basic knowledge in site structure,
content organization, the selection of keywords, and writing page descriptions. This
can be as a basis for further learning and will help you establish a strong foundation
for your company's website.
1.10.3 How to Structure Your Website
For most small to medium-sized businesses, there are two types of content sections
you'll need to think about.
websites.
-specific sections: those sections those are unique to your
Business. They may be sub-sections of the above.
A. Common Section: these will contain general information about the organization.
It is up to you to decide which sub-elements should be included. You may consider
following points in this section:
a. About us: This section gives information about the organization. You will see this
on almost every commercial website, both small and big. It is a common practice to
know the organization you are dealing with. This section helps outside world to know
about you. This information might fit on a single page or stretch to several pages.

Following element might be included in this part:


 Who are you?
 Company/organization History
 Company/organization profile
 Mission Statement
 Contact us- You should include as many ways as possible for customers to
 contact you as possible. This part must be updated regularly. The contact
 information must include:
 Telephone and fax numbers
 Email addresses
 Email forms
 Physical address
 Emergency contact details
b. Products and Services:
It is a general practice to include information about their products or services on the index page (the front or
home page), but it‘s important to also dedicate separate section of your site to your products. This will help
your customers find your products and services easily and allow them to research and assess your quickly.
B. Organization-specific sections:
The best way to go about creating organization specific sections for your website is
to follow the same general structure as above by creating logical subsections for each
section. The first page of a subsection should contain general information on the
subject, as well as links to more detailed information if your visitors require it. For
example, a special library site may have special collection on specific subjects that
may contain following sub-subject:
 Special collection on the subject
 Period it covers
21
 Uniqueness of record
 Information Media
 Accessibility

1.10.4 The 5 Golden Rules


5 golden rules of web design are
Purpose
Every website needs a purpose and no, to tell people about my business isn‘t a good purpose. The purpose
of web design always comes down to the purpose of the website that can be boiled down to one thing.
The more specific the purpose is, the better off your project will go. There should be one overall purpose
that‘s very focused and then every page should have a purpose that plays into that larger purpose.
Every piece of content, every design element, every everything should have a purpose behind it and play
into the overall purpose.
The purpose you decide for every piece and the overall site usually flows into one well-crafted call to
action. What are the website visitors supposed to do? What the heck can they do?
I‘ve seen way too many websites that seemed to have been created just for the sake of creating a website.
No plan, no focus, and no goal.

They‘re just a purposeless mass of content on the internet that helps no-one. That‘s why every website
needs and deserves a purpose that goes beyond the client‘s (or your) decision that a website is needed.
Consistency
A website should be designed to be one cohesive, simple, consistent entity on the internet. That means the
overall purpose (see above) is consistent across the website.
Focus on creating one brand that looks like it all belongs to the same company. That means visuals should
be in a similar style, colors consistent, and most of all fonts should be few and consistent.
Good web design is extremely important, but it only works if there‘s consistency in it all.
Ease
How much does the website get out of the way and let the user accomplish their goal?
There‘s the purpose of the website which is golden rule number 1. This one matter because the purpose
needs to be easy to achieve.
The goal should be obvious for each page and the user shouldn‘t have to fight to accomplish their goal.
Every website is going to have a unique goal and it needs to be easy to accomplish.
Speed
How fast your website is deciding how easy it is to use and it determines if the goal is even met for the user.
People are impatient and a fast website will help keep the user focused and continuing their journey to
complete their goal.
If your website isn‘t showing something to the user within 2-3 seconds, then the whole website is likely to
never be seen.
I can‘t tell you how many times I‘ve seen do it yourself website that have a giant video in the background
which makes it take 8 seconds to load. That just won‘t do.
When we do affordable web design for our clients, one of our major focuses is on speed to make sure it‘s as
fast as possible. Google‘s goals for speed can be a bit lofty but there is a fine balance.
Speed without goals and tracking is not good. That seems to be what Google wants but that can be overall
harmful to the internet, no good. There‘s a fine balance but that‘s something that every web designer needs
to figure out properly.
Revise
The final golden rule of web design is another important rule.
A website is never done.
A successful website must always be revised, updated, and improved. That means new content should
regularly be published that is helpful and adds to the value of the website.
It also means there should be constant revisions of the current content including the newer content that is
posted. Time should be set aside each month to make some revisions no matter how minor.

22
Testing and improving on a regular basis is the cornerstone to a successful website and a website that ranks
well. Google is one search engine that rewards helpful and current content. It knows when you update
content and will reward your website in search results if those updates happen regularly.
One reason we offer unlimited minor updates in each of our plans is because it‘s so essential to make those
updates. A picture here, a word there, no matter how small it contributes to an always updating website.

1.11 Summary
This lesson covers the concept of World Wide Web (WWW) ,web achitecture and how to
use linking the documents and to determine dynamic updates of web pages and Basic
principles involved in developing a web site, Concept of protocol, concept of web Designing

KEYWORDS
World Wide Web: It is a system of interlinked hypertext documents accessed via the Internet.
IP address: An IP address defines a device‘s connection to a network.
URI (Uniform Resource Identifier): It identifies an object on the Internet.
URL (Uniform Resource Locator): It is a specification for identifying an object such as a file, newsgroup,
and CGI program or e-mail address by indicating the exact location on the internet.
URN (Uniform Resource Name): It is a method for referencing an object without declaring the full path to
the object.

SELF-ASSESSMENT QUESTIONS

Short Answer Questions


1.What do you mean by WWW? How is it differing from internet? How has World Wide Web
(WWW) evolved over last 15 years?
2. What is the difference between node and hosts?
3.What is IP address?
4. What are the differences between SMTP and POP?
5. What is the primary goal of ARPANET?

Long Answer Questions


1. Explain in detail the basic internet protocols.
2. Explain the concept of web clients and web browsers.
3. Explain FTP protocol in detail.
4. What is SMTP? Explain the working of SMTP in detail.
5. Explain the architecture of WWW in detail
6. Explain in detail Golden Rules of Web Designing
.FURTHER READINGS

Harvey & Paul Diestel& Associates, Harvey Deitel and Abbey Diestel, ―Internet and World Wide
Web - How to Program‖, Fifth Edition, Pearson Education, 2011.

23
UNIT-II – UI DESIGN

CONTENTS
Learning Objectives
Learning Outcomes
Overview
2.1 Introduction to HTML
2.2 Basic markup tags
2.3 SVG Element
2.4 Cascading Style Sheets
2.5 The CSS Box Model
2.6 CSS Margin
2.7 Padding
2.8 Class Selectors
2.9 Inline and Block Elements
2.10 Structuring pages using Semantic Tags
Summary
Keywords
Self-Assessment Questions
Further Readings

LEARNING OBJECTIVES
After studying this lesson, you should be able to:
 Illustrate HTML Application
 Understand the different types of Tags
 Learn how CSS can be used

LEARNING OUTCOMES
Upon completion of the lesson, students can demonstrate a good understanding of:
o Concept of HTML
o Explain Different types of Tags
o Analyzing CSS Stylesheets with different formats.
o Concept of CSS Pseudo selectors.

24
2.1 Introduction to HTML: -
HTML means Hypertext Markup Language. In 1960 Ted Nelson introduced Hypertext. HTML is a
scripting language which is used to create web pages. If you are thinking of creating your own web pages,
you need to know at least basic HTML. These HTML documents are plain text files; user can create these
documents using text editor like Notepad or Edit.
HTML is a hypertext Language because it supports font styled text, pictures, graphics, and animations and it
provides hyperlinks that used to browse the Internet easily. Text becomes hypertext with the addition of links
that connects other hypertext documents.
Hypertext is a text augmented with links-pointers to other pieces of text, possible elsewhere in the same
document (internal linking) or in another document (external linking).
2.1.1 Rules to write HTML Code: -
 Every HTML document begins with start tag is <HTML> terminates with an ending tag is </HTML>
 HTML documents should be saved with the extension .html or .htm.
 A tag is made up of left operator (<), a right operator (>) and a tag name between these two operators.
 If you forget to mention the right operator (>) or if you give any space between left operator and tag
name browser will not consider it as tag.
 At the same time if browser does not understand the tag name it just ignores it, browser won ‟t
generates any errors.
 HTML language is not case sensitive; hence user can write the code in either upper case or lower
case. No difference between <HTML> and <html>

Syntax of a tag:
<Tag name [parameters=value]>

Ex: HR is a tag name that displays a horizontal ruler line.


<HR> (No parameters, no value)
<HR ALIGN=CENTER> (Tag with parameter and value for the parameter)
<HR WIDTH=‖30%‖ SIZE=100 ALIGN=RIGHT> (Tag with more parameters with
their values)

2.1.1.1 Different types of Tags:


1. Singleton tags
2. Paired tags
Singleton tag does not require an ending tag. (Ex: <HR>
Paired tag required an ending tag, which is like opening tag except backslash before thetag
name (Ex: <HTML> is opening tag, then ending tag is </HTML>
Comments in HTML:
An HTML comment begins with ―<! --―and ends with<h ―-->‖. There should not
bea space between angular bracket and exclamation mark.
Creating HTML Page:
The Following steps are needed to create a HTML page
Step 1: Open any text editor like Notepad, Edit, Word etc.
Step 2: Use the file menu to create a new document (File New) and type the following code
<HTML>
<HEAD>
25
<TITLE>Example1 </TITLE>
<BODY>
Hello III IT, this is your first web page. - Raju
</BODY>
</HTML>
Step 3: Go to the file menu and choose save as option (File->save as) and give the name of
thefile as ―example1.html‖ under root directory (C:)( or any valid path)
Step 4: After saving, an internet explorer icon will be displayed as shown below

Step 5: Double click to execute it. The output displayed following

Fig 2.1 basic creation of web page


2.2 Basic HTML tags

1. Body tag: -
Body tags contain some attributes such as bgcolor, background etc. bgcolor is used for
background color, which takes background color name or hexadecimal number and #FFFFFF
and background attribute will take the path of the image which you can place as the
background image in the browser.

<body bgcolor=‖ #F2F3F4‖ background= ―c:\amer\imag1.gif‖>

2. Paragraph tag: -
Most text is part of a paragraph of information. Each paragraph is aligned to the left, right or
center of the page by using an attribute called as align.

<p align=‖ left‖ | ―right‖ | ―center‖>

3. Heading tag: -
HTML is having six levels of heading that are commonly used. The largest heading tag is
<h1>. The different levels of heading tag besides <h1> are <h2>, <h3>, <h4>, <h5> and
<h6>. These heading tags also contain attribute called as align.

<h1 align=‖ left‖ | ―right‖ | ―center‖> ....... <h2>

26
4. hr. tag: -
This tag places a horizontal line across the system. These lines are used to break the page.
This tag also contains attribute i.e., width which draws the horizontal line with the screen size
of the browser. This tag does not require an end tag.

<hr width=‖50%‖>.

5. base font: -
This specifies format for the basic text but not the headings.

<base font size=‖10‖>

6. font tag: -
This sets font size, color, and relative values for a particular text.

<font size=‖10‖ color=‖ #f1f2f3‖>

7. bold tag: -
This tag is used for implementing bold effect on the text

<b> .......... </b>

8. Italic tag: -
This implements italic effects on the text.

<i> ........ </i>

9. strong tag: -
This tag is used to always emphasized the text

<strong> ............ </strong>

10. tt tag: -
This tag is used to give typewriting effect on the text

<tt> ......... </tt>

11. sub and sup tag: -


These tags are used for subscript and superscript effects on the text.

<sub> .............</sub>
<sup> .............</sup>

12. Break tag: -


This tag is used to the break the line and start from the next line.

<br>

13. &amp &lt &gt &nbsp &quot: -


These are character escape sequence which are required if you want to display characters that
HTML uses as control sequences.

Example: < can be represented as &lt.

27
14. Anchor tag: -
This tag is used to link two HTML pages; this is represented by <a>
<a href=‖ path of the file‖> some text </a>
href is an attribute which is used for giving the path of a file which you want to link.

Example 1: HTML code to implement common tags.


mypage.html
<html>
<head> <! -- This page implements common html tags -->
<title> My Home page </title>
</head>
<body >
<h1 align="center"> ST ANN‟S COLLEGE OF ENGINEERING & TECHNOLOGY</h1>
<h2 align="center"> Chirala</h2>
<basefont size=4>
<p> This college runs under the <tt>management</tt> of <font size=5> <b><i>&quot
SACET&quot &amp </i></b></font><br>
it is affiliated to <strong> JNTUK</strong>
<hr size=5 width=80%>
<h3> <u>&lt Some common tags &gt</u> </h3><br>
</body>
</html>

Text Styles or Cosmetic tags: - HTML provides a numerous range of tags for formatting
thetext. If you want to format the text with different styles, just you include these tags one
by one before text.
<B>………</B> Bold Text
<U>…….... </U> Underline Text
<I>………. </I> Displays as Italics
<EM>………</EM> For Emphasis (New Standard for Italics)
<STRONG>………</STRONG> Strong or Bold text (New Standard for Bold)
<S>………. </S> or <DEL>……. </DEL> Strikes the text
<SAMP>………</SAMP> Code sample text
<VAR>………. </VAR> Small fonts, fixed width
<ADDRESS>……. </ADDRESS> Like address model (Looks like italics)
<PRE>……. </PRE> Considers spaces, new lines etc. As it is prints the information

Scrolling Text Tag: -


<marquee> ................ </marquee> Displays scrolling text in a marquee style.
Marquee tag attributes: -
a) align: sets the alignment of the text relative to the marquee. Set to top(default), middle
or bottom.
b) behavior: Sets how the text in the marquee should move, It can be scroll(default),
slide (text enters from one side and stops at the other end), or alternative(text seems
tobounce from one side to other)
c) bicolor: sets the background color for the marquee box
d) direction: sets the direction of the text for scrolling. It can be left(default), right,
down,or up.

28
Example: -
<marquee align=‖ middle‖ behavior=‖ slide‖ bgcolr=‖ red‖ direction=‖ down‖>Raju</marquee>

Blinking text Tag: -


<blink>………</blank> displays enclosed text as blinking on and off approximately
once a second.
Linking in HTML: -
Text becomes hypertext with the addition of links which connect separate locations
within a collection of hypertext documents.

……………

Hyperlinks can be applied for either text or images. Links may connect several web pages
of a web site. Links can connect web pages on the same or different servers.
Navigation between pages became easier because of links. Information in the same page also
connected through links (internal links).

<A> ............. </A>

Anchor tag is used for creating links. Minimum it requires a parameter i.e., HREF, which
indicates the destination document. Other parameters Name and target can be useful for
identification for anchor tag and the location of a frame where target page is to be displayed
respectively. Name and target tag are optional.
Syntax: <A HREF=‖ address‖ NAME=‖id‟ TARGET=‖target window‖>
………….
………….. id=Text that displays as link
</A>

HREF Parameter: -
If HREF is included, the text between the opening and closing anchor element
that between <A> and </A> becomes hypertext. If users click on this text, they are moved
to specified document.
Ex: -

Example:
<html>
<A >HREF=www.vaneshdoc.com>Publishers</A> Result displayed as Publishers When the user click
on this text, Publishers web site is displayed on the browser.

Create a HTML web page that connect web pages created through hyperlinks.
<head>
<title> Navigation </title>
</head>
<body bgcolor=cyan>
<h1 align=center>Overceas Publisher </h1>
<h3 align=center>All pages connected through links</h3>
<center>
29
<p>Company Details<A HREF=‖ 1.html‖>My Company</A>
<p>Book Details <A HREF=‖ 2.html‖>My Book</A>
<p> Author Details <A HREF=‖ 3.html‖> Author</A>
</center>
</body>
</html>

Fig 2.2 connect web page through hyperlink


Color and Image:
Color can be used for background, elements and links. To change the color of links or of
the page background hexadecimal values are placed in the <body> tag.
<body bgcolor = ―#nnnnnn‖ text = ―#nnnnnn‖ link= ―#nnnnnn‖ vlink= ―#nnnnnn‖ alink
= ―#nnnnnn‖>
The vlink attribute sets the color of links visited recently, alink the color of a currently
active link. The six figure hexadecimal values must be enclosed in double quotes and
preceded by a hash(#).
Images are one of the aspect of web pages. Loading of images is a slow process, and if
too many images are used, then download time becomes intolerable. Browsers display a
limited range of image types.
<body background = ―URL‖>
This tag will set a background image present in the URL.
Another tag that displays the image in the web page, which appears in the body of the
text rather than on the whole page is given below
<img src=‖URL‖ height=‖n‖ width=‖n‖ align = ―top‖ | ―center‖ | ―bottom‖ >
Example 4: HTML code that implements color and image
<!DOCTYPE html>
<html>
<body>
<h1 style="background-color:Tomato;">Tomato</h1>
<h1 style="background-color:Orange;">Orange</h1>
<h1 style="background-color:DodgerBlue;">DodgerBlue</h1>
<h1 style="background-color:MediumSeaGreen;">MediumSeaGreen</h1>
<h1 style="background-color:Gray;">Gray</h1>
<h1 style="background-color:SlateBlue;">SlateBlue</h1>
<h1 style="background-color:Violet;">Violet</h1>
<h1 style="background-color:LightGray;">LightGray</h1>
</body>
</html>

30
Fig 2.3 Output for colour and image
Example 5: HTML code that implements background image
<html>
<head> <! -- This page implements background image -->
<title> My Home page </title>
</head>
<body background="C:\Documents and Settings\All Users\Documents\My Pictures\Sample
Pictures\Blue hills.jpg">
<h1 align="center"> This is my background Image</h1>
</body>
</html>

Fig 2.4 Output of background Image


2.2.1 Lists:
One of the most effective ways of structuring a web site is to use lists. Lists provides straight
forward index in the web site. HTML provides three types of list i.e., bulleted list, numbered
list and a definition list. Lists can be easily embedded easily in another list to provide a
31
complex but readable structure. The different tags used in lists are explained below.
Unordered Lists: -
Unordered lists are also called unnumbered. lists. The Unordered list elements are used to
represent a list of items, which are typically separated by white space and/or marked by
bullets. Using <UL> tag does creation of unordered lists in HTML. Which is paired tag, so it
requires ending tag that is </UL>. The list of items are included in between <UL>…..</UL>.
The TYPE attribute can also be added to the <UL> tag that indicates the displayed bullet
along with list of item is square, disc or circle. By default, it is disc.

Syntax:- <UL [TYPE={square/disc/circle}]>


<LI>item name1
<LI>item name2
…………………..
Write a HTML program for displaying names of B.Tech Courses with unordered list

Example:
<LI>item namen
</UL>

default bullets and names of PG Courses with square bullets.

<html>
<head>
<title>Unordered Lists</title>
</head>
<body bgcolor=‖tan‖>

<ul>
<h1>B.Tech Courses
<h3>

<li>CSE
<li>IT
<li>ECE
<li>EEE
<li>MECH
</ul>
</h3>
<h1>PG Courses
<h3>
<ul type=‖ square‖>
<li>MCA
<li type=‖ circle‖>MBA
<li>M.Tech
</ul>
</h3>
</body>
</html>

32
Fig 2.5 Output for unordered list

Ordered Lists: -
Ordered lists are also called sequenced or numbered lists. In the ordered list the list of item
have an order that is signified by numbers, hence it sometimes called as number lists.
Elements used to present a list of items, which are typically separated by white space and/or
marked by numbers or alphabets. An orders list should start with the <OL> element, which is
immediately followed by a <LI> element which is same as <LI> in unordered list. End of
ordered lists is specified with ending tag </OL>.

Different Ordered list types like roman numeral list, alphabet list etc. can be specified with
TYPE tag. Another optional parameter with <OL> tag is START attribute, which indicates
the starting number or alphabet of the ordered list. For example, TYPE=‖ A‖ and START=5
will give list start with letter E. The TYPE attribute used in <LI>, changes the list type for
particular item. To give more flexibility to list, we can use VALUE parameter with
<LI>tag that helps us to change the count for the list item and subsequence items.

Syntax: -
<OL [type= {―1‖ or ―I‖ or ―a‖ or‖ A‖ or ―i‖}] START=n>
<LI>item name1
<LI>item name2

<LI>item namen
</OL>
Different Ordered list types
Type=‖1‖ (default) e.g.1,2,3,4….
Type=‖A‖ Capital letters e.g.A,B,C…
Type=‖a‖ Small letters e.g. a,b,c……
Type=‖ I‖ Large roman letters e.g. I, II, III,…

Example: -
<html>
<head>
33
<title>Ordered Lists</title>
</head>
<body bgcolor=‖tan‖ text=‖ blue‖>
<h2> Types of Fruits
<h4>
</h4>
<OL>

</OL>

<LI>Orange
<LI>Apple
<LI>Grape
<LI>Banana<h2>Types of colors
<h4>
<OL type=‖A‖ START=5>
<LI>Red
<LI>Green
<LI>Blue
<LI>Yellow
</OL>
</h4>
</body>
</html>

Fig 2.6 Output for ordered List


Other Lists: -
There are several lists in HTML, some of them are definition list and Directory List.
Definition List: -
<DL>………</DL>
A Definition list is alist of definition terms <DT> and corresponding Difinition
Description<DD> on a new line. To create a definition, it must start with <DL> and
immediately followed by the first definition term <DT>
Example: -

34
<html>
<head>
<title>Definition List</title>
<body>
<DL>
<DT>HTML
<DD> HTML is a scripting language which is used to create web pages. if you
are thinking of creating your own web pages, you need to know at least basic HTML.
<DT>SGML
<DD>SGML, Standard Generalized Markup Language
</DL>
</body>
</html>

Fig 2.7 Output of Directory List


Directory List: -

A Directory list element is used to present a list of items containing up to 20


characters each. Items in a Directory List may be arranged in columns, typically 24 characters
wide. A Directory List being with <DIR>element, which is immediately followed by a
<LI>element. This tag is a deprecated tag, so it is not preferable to use. Hence, use <UL>
instead of <DIR> Other information
<DIR>
<LI>Contacts-2043240
<LI>Business-4123412
<LI>Personal-3123122
</DIR>
Nested Lists: - Lists can be nested that is Nested Lists is list within another list.
2.2.2 Tables:
Table is one of the most useful HTML constructs. Tables are found all over the
web application. The main use of table is that they are used to structure the
pieces of information and to structure the whole web page. Below are some of the tags
used in table.

<table align=‖ center‖ | ―left‖ | ―right‖ border=‖ n‖ width=‖n%‖ cell

35
padding=‖n‖cell spacing=‖n‖>
………………
</table>
Everything that we write between these two tags will be within a table. The attributes of
the table will control in formatting of the table. Cell padding determines how much space
there is between the contents of a cell and its border, cell spacing sets the amount of
white space between cells. Width attribute sets the amount of screen that table will use.
<tr> …. </tr>
This is the sub tag of <table> tag, each row of the table must be delimited by these tags.

<th>……</th>
This is again a sub tag of the <tr> tag. This tag is used to show the table heading .

<td>…..</td>
This tag is used to give the content of the table.

Example 3: HTML code showing the use of table tag


<html>
<head>
<title> table page</title>
</head>
<body>
<table align="center" cellpadding="2" cellspacing="2" border="2">
<caption> Time Table for III year IT </caption>
<tr><th> 1 period </th>
<th> 2 peiord </th>
<th> 3 peiord </th>
<th> 4 peiord </th>
</tr>
<tr>
<td> wt </td>
<td> uml</td>
<td> MT</td>
<td> DMDW</td>
</tr>
</table>
</body>
</html>

Fig 2.8 Output of Table Tag


36
Complex HTML Tables and Formatting: -
You can add background color and background images by using bgcolor and
background attributes respectively. Spanning of cells is possible that is you can merge some
sequence of rows or columns with the help of ROWSPAN or COLSPAN attributes
respectively. For example, <th COLSPAN=‖2‖>widened to span two cells. VALIGN
attributeis used for vertical alignment formats, and it accepts the values ―top‖, ―middle‖,
―bottom‖ and―baseline‖.
Example:
<html>
<head>
<title> table</title>
</head>
<body>
<center>
<table border=‖2‖>
<caption>Supermarket Details</caption>
<tr>
<th colspan=3 bgcolor=‖tan‖ align=‖center‖>Items
Available</th> Name<th>Rate</tr>
<tr><td>1<td>Close Up Paste<td>15-00</tr>
</tr> <tr><td>2<td>Pears Soap<td>30-00</tr>
<tr><th <tr><td>3<td>Drink<td>10-00</tr>
>S.No< </table>
th>Item </center>
</body>
</html>

Fig 2.9 Output of Table Formatting


37
2.2.3 Frames:
Frames provide a pleasing interface which makes your web site easy to navigate.
When we talk about frames actually we are referring to frameset, which is a special
type ofweb page.
Simply frameset is nothing but collection of frames. Web page that contains frame
element iscalled framed page. Framed page begins with <frameset> tag and ends with
</frameset>.
Each individual frame is identified through <frame> tag. Creation of framed page is
very simple. You can nest the framesets. First you decide how you want to divide your
webpageand accordingly define frame elements.
Consider the following diagrams, first form divides into two columns and the
secondform divides into three rows.

Two columns frameset Three rows

frameset In order to divide into two columns we can use the following

syntax
<frameset cols=‖25%,75%>
<frame name=‖disp‖ src=‖1.html‖>
<frame name=‖res‖ src=‖ 2.html‖>
</frameset>
In the second diagram we have three rows so by using rows parameter of frameset, we
candivide logically the window into three rows.
<frameset rows=‖20%,*,10%>
<frame name=‖first‖ src=‖1.html‖>
<frame name=‖second‖ src=‖2.html‖>
<frame name=‖third‖ src=‖3.html‖>
</frameset>
According to above code, first row occupies 20% of the window, third row occupies
10% ofthe window, second row * represents remaining area that is 70% of the
window.
Nested Framesets: -
Sometimes it is required to divide your window into rows and columns, then
there isrequirement of nested framesets. Frameset with in another frameset is known as
nested frameset.
The purpose of NAME parameter in frame tag in the above example is nothing but
main importance is if we have some links in left side and you want to display
respective pages inthe right-side frame, then name is essential. Using target parameter
of Anchor(A) tag as follows users can specify name of frame.
Example:
First.html
<frameset rows=‖20%,*‖>
<frame name=‖fr1‖ src=‖frame1.html‖>
38
<frameset cols=‖25%,*‖>
<frame name=‖fr2‖ src=‖frame2.html‖>
<frame name=‖fr3‖ src=‖frame3.html‖>
</frameset>
</fra
meset>
Frame1.html
<html>
<body>
<center><h1> College branches</h1></center>
</body>
</html
>
Frame
2.html
<html>
<body bgcolor=‖green‖>
<ul>

</ul>
</body>
</html> Frame3.html
<html>
<li>CSE
<li>EEE
<li>ECE
<A href=‖example2.html‖ target=‖fr3‖><li>IT</A>

<body text=‖white‖ bgcolor=‖tan‖>


<h1>Profile</h1>
</body>
</html>

Fig 2.10 Output of Nested Frameset


39
2.2.4 Forms:
Forms are the best way of adding interactivity of element in a web page. They are
usually used to let the user to send information back to the server but can also be
used to simplify navigation on complex web sites. The tags that use to implement
forms are as follows.

<forms action=‖URL‖ method = ―post‖ | ―get‖>…….</form>

When get is used, the data is included as part of the URL. The post method encodes
the data within the body of the message. Post can be used to send large amount of data,
and it is moresecure than get. The tags used inside the form tag are:

<input type = ―text‖ | ―password‖ | ―checkbox‖ | ―radio‖ | ―submit‖


name=‖s
string‖value=‖string‖ size=‖ n‖>

In the above tag, the attribute type is used to implement text, password, checkbox,
radio andsubmit button.

Text: It is used to input the characters of the size n and if the value is given than it is
used as adefault value. It uses single line of text. Each component can be given a
separate name using the name attribute.

Password: It works exactly as text, but the content is not displayed to the screen,
instead an *is used.

Radio: This creates a radio button. They are always grouped together with a same name
butdifferent values.

Checkbox: It provides a simple checkbox, where all the values can be selected unlike
radiobutton.

Submit: This creates a button which displays the value attribute as its text. It is used to
sendthe data to the server.

<select name=‖string‖>…..</select>
This tag helps to have a list of item from which a user can choose. The name of the
particular select tag and the name of the chosen option are returned.

<option value=‖string‖ selected>……</option>


The select statement will have several options from which the user can choose. The
values will be displayed as the user moves through the list and the chosen one returned
to the server.

<textarea name=‖string‖ rows=‖n‖ cols=‖n‖>…….</textarea>


This creates a free format of plain text into which the user can enter anything they like.
Thearea will be sized at rows by cols but supports automatic scrolling.

40
Example 6: HTML code that implements forms
<html>
<head>
<title>form</title>
</head>
<body>
<p align="left">Name:<input type="text" maxlength=30 size=15>
<p align="left">Password:<input type="password" maxlenght=10 size=15>
<p align="left">Qualification: <br><input type="checkbox" name="q"
value="be">B.E
<input type="checkbox" name="q" value="me">M.E
<p align="left">Gender:<br> <input type="radio" name="g" value="m">Male
<input type="radio" name="g" value="f">Female
<p align="left">course:<select name="course" size=1>
<option value=cse selected>CSE
<option value=it>CSIT
</select>
<p align="left">Address:<br><textarea name="addr" rows=4 cols=5
scrolling=yes></textarea>
<p align="center"><input type="submit" name="s" value="Accept">
<p align="center"><input type="reset" name="c" value="Ignore">
</body>
</html>
2.2.5 HTML5 Audio Tag
The HTML <audio> element is used to embed sound content in documents. It may contain one or
more audio sources, represented using the src attribute or the <source> element: the browser will
choose the most suitable one.
HTML5 most commonly used audio formats are ogg, mp3 and wav. You can use <source> tag to
specify media along with media type and many other attributes. An audio element allows multiple
source elements and browser will use the first recognized format
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The HTML5 audio Element</title>
</head>
<body>
<audio controls="controls">
<source src="images/html5-audio-mp3.mp3" type="audio/mpeg">
<source src="images/html5-audio-mp3.ogg" type="audio/ogg">
</audio>
</body>
</html>

41
Table 2.1 Audio Tags
Format MIME-type

MP3 audio/mpeg

OGG audio/ogg

WAV audio/wav

Attribute Value Description

autoplay autoplay Specifies that the audio will start playing as soon as it is ready

controls controls Specifies that audio controls should be displayed (such as a play/pause button
etc)
loop loop Specifies that the audio will start over again, every time it is finished

muted muted Specifies that the audio output should be muted

preload auto Specifies if and how the author thinks the audio should be loaded when the page
metadata loads
none

src URL Specifies the URL of the audio file

2.2.6 HTML5 Video Tag


HTML5 <video> element provides a standard way to embed video in web pages. However, the
video element is relatively new, but it works in most of the modern web browsers. The following
example simply inserts a video into the HTML5 document, using the browser default set of
controls, with one source.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The HTML5 video Tag</title>
</head>
<body>

<video controls>
<source src="images/html5-video.mp4" type="video/mp4">
<source src="images/html5-video.ogg" type="video/ogg">
</video>
</body>
</html>
42
HTML Tags Chart
To use any of the following HTML tags, simply select the HTML code you'd like and copy and
pasteit into your web page.
Table 2.2 HTML Tags

Tag Name Code Example Browser View


<!--This can be viewed in the HTML part of adocument-
<!-- comment Nothing will show (Tip)
->
<a href="http://www.domain.com/">Visit Our
<a - anchor Visit Our Site (Tip)
Site</a>
<b> bold <b>Example</b> Example
<big> big (text) <big>Example</big> Example (Tip)
body of
HTML <body>The content of your Contents of your webpage (Tip)
<body>
document HTML page</body>

The contents of your webpage


line The contents of your page<br>The contentsof your The contents of your webpage
<br>
break page

<center>This will center your This will center yourcontents


<center> center
contents</center>
<dl> Definition Term
<dt>Definition Term</dt> Definition of theterm
definition
<dd> descripti on <dd>Definition of the term</dd> Definition Term
<dt>Definition Term</dt> Definition of theterm
<dd>Definition of the term</dd>
</dl>
<dl> Definition Term
<dt>Definition Term</dt> Definition of theterm
definition <dd>Definition of the term</dd> Definition Term
<dl>
list <dt>Definition Term</dt> Definition of theterm
<dd>Definition of the term</dd>
</dl>
<dl> Definition Term
<dt>Definition Term</dt> Definition of theterm
definition <dd>Definition of the term</dd> Definition Term
<dt>
term <dt>Definition Term</dt> Definition of theterm
<dd>Definition of the term</dd>
</dl>
This is an <em>Example</em> of usingthe This is an Example of usingthe emphasis tag
<em> emphasis
emphasis tag
embed <embed src="yourfile.mid" width="100%"
<embed>
object height="60" align="center"> (Tip)

<embed src="yourfile.mid" autostart="true" Music will begin playing when your page is
embed hidden="false" loop="false"> loaded and will only play one time.A control
<embed> object <noembed><bgsound src="yourfile.mid" panel will be displayed to enable your visitors
loop="1"></noembed> to stop the music.

<font face="Times New


<font> font Example (Tip)
Roman">Example</font>
<font face="Times New Roman"
<font> font
size="4">Example</font> Example (Tip)
43
<font face="Times New Roman" size="+3"
<font> font
color="#ff0000">Example</font> Example (Tip)

<form action="mailto:[email protected]">
Name: <input name="Name" value=""
Name: (Tip)
size="10"><br>
Email: <input name="Email" value="" Email:
<form> form size="10"><br>
<center><input type="submit"></center> Submit
</form>

<h1> heading 1 <h1>Heading 1 Example</h1>


<h2> heading 2 <h2>Heading 2 Example</h2>
<h3> heading 3 <h3>Heading 3 Example</h3>
<h4> heading 4 <h4>Heading 4 Example</h4>
<h5> heading 5 <h5>Heading 5 Example</h5>
<h6> heading 6 <h6>Heading 6 Example</h6>

heading of
HTML <head>Contains elements describing the
<head> document Nothing will show
document</head>

Contents of your webpage (Tip)


horizontal
<hr> <hr />
rule
Contents of your web page

Contents of your web page


horizontal
<hr> rule <hr width="50%" size="3" />
Contents of your web page
Contents of your web page
horizontal
<hr> rule <hr width="50%" size="3" noshade />
Contents of your web page
<hr> (Internet Contents of your web page
horizontal <hr width="75%" color="#ff0000" size="4"
Explorer)
rule /> Contents of your web page
<hr> (Internet Contents of your web page
horizontal <hr width="25%" color="#6699ff" size="6"
Explorer)
rule />
Contents of your web page
<html>
<head>
<meta>
hypertext
<html> markup <title>Title of your web page</title> Contents of your web page
language </head>
<body>HTML web page contents
</body>
</html>
<i> italic <i>Example</i> Example
<img src="Earth.gif" width="41" height="41"
<img> image border="0" alt="text describingthe image" />
(Tip)
Example 1:
Example 1: (Tip)
<form method=post action="/cgi-
input bin/example.cgi">
<input> field <input type="text" size="10" Submit

44
maxlength="30">
<input type="Submit" value="Submit">
</form>
Example 2:

<form method=post action="/cgi-


Example 2: (Tip)
bin/example.cgi">
<input> <input type="text" style="color: #ffffff;
(Internet input
field font-family: Verdana; font-weight: bold; font-size: 12px; Submit
Explorer)
background-color: #72a4d2;" size="10"
maxlength="30">
<input type="Submit" value="Submit">
</form>
Example 3:

<form method=post action="/cgi-


bin/example.cgi">
<table border="0" cellspacing="0" Example 3: (Tip)
cellpadding="2"><tr><td bgcolor="#8463ff"><input
input
<input> type="text" size="10" maxlength="30"></td><td
field
bgcolor="#8463ff" valign="Middle"> <input
type="image" name="submit"
src="yourimage.gif"></td></tr> </table>
</form>

Example 4:
Example 4: (Tip)
<form method=post action="/cgi-bin/example.cgi">
Enter Your Comments:<br>
input <textarea wrap="virtual" name="Comments"rows=3
<input> field cols=20 maxlength=100></textarea><br>
<input type="Submit" value="Submit">
<input type="Reset" value="Clear"> Submit Clear
</form>

Example 5:

<form method=post action="/cgi-


bin/example.cgi">
<center> Example 5: Tip)
Select an option:
<select> Select an option 2
option:
<option >option 1</option>
input <option selected>option 2</option> Submit
<input>
field <option>option 3</option>
<option>option 4</option>
<option>option 5</option>
<option>option 6</option>
</select><br>
<input type="Submit"
value="Submit"></center>
</form>
input Example 6: Example 6: (Tip)
<input>
field

45
<form method=post action="/cgi- Select an option:Option 1
bin/example.cgi">
Select an option:<br> Option 2
<input type="radio" name="option"> Option1
<input type="radio" name="option"checked> Option 3 Select an option:
Option 2
Selection 1
<input type="radio" name="option"> Option3
<br> Selection 2
<br>
Selection 3
Select an option:<br>
<input type="checkbox" name="selection">Selection 1
<input type="checkbox" name="selection"checked>
Selection 2
<input type="checkbox"
Submit
name="selection"> Selection 3
<input type="Submit" value="Submit">
</form>

Example 1: Example 1: (Tip)


<menu>
<li type="disc">List item 1</li>  List item 1
<li type="circle">List item 2</li> o List item 2
<li type="square">List item 3</li>  List item 3
</MENU>
<li> list item
Example 2: Example 2:

<ol type="i"> i. List item 1


<li>List item 1</li> ii. List item 2
<li>List item 2</li> iii. List item 3
<li>List item 3</li> iv. List item 4
<li>List item 4</li>
</ol>
<head>
<link rel="stylesheet" type="text/css"
<link> link href="style.css" />
</head>

<marquee
<marquee bgcolor="#cccccc" loop="-1"
> scrolling scrollamount="2" width="100%">Example
(Internet text Marquee</marquee>
Explorer)

(Tip)
<menu>
 List item 1
<li type="disc">List item 1</li>
<menu> <li type="circle">List item 2</li> o List item 2
menu
 List item 3
<li type="square">List item 3</li>
</menu>
<meta name="Description"
content="Description of your site">
<meta> meta Nothing will show (Tip)
<meta name="keywords" content="keywords
describing your site">
<meta HTTP-EQUIV="Refresh"
<meta> meta CONTENT="4;URL=http://www.yourdomain.com/"> Nothing will show (Tip)

<meta http-equiv="Pragma" content="no-cache">


<meta> meta Nothing will show (Tip)

<meta> meta <meta name="rating" content="General"> Nothing will show (Tip)

46
<meta> meta <meta name="robots" content="all"> Nothing will show (Tip)
<meta name="robots"
<meta> meta Nothing will show (Tip)
content="noindex,follow">
Numbered Numbered

<ol> 1. List item 1


<li>List item 1</li> 2. List item 2
<li>List item 2</li> 3. List item 3
<li>List item 3</li> 4. List item 4
<li>List item 4</li>
</ol> Numbered Special Start
Numbered Special Start
5. List item 1
<ol start="5"> 6. List item 2
<li>List item 1</li> 7. List item 3
<li>List item 2</li> 8. List item 4
<li>List item 3</li>
<li>List item 4</li> Lowercase Letters
</ol>
a. List item 1
Lowercase Letters
b. List item 2
c. List item 3
<ol type="a"> d. List item 4
<li>List item 1</li>
<li>List item 2</li>
Capital Letters
<li>List item 3</li>
<li>List item 4</li>
</ol> A. List item 1
B. List item 2
ordered
<ol> Capital Letters C. List item 3
list
D. List item 4
<ol type="A">
<li>List item 1</li> Capital Letters SpecialStart
<li>List item 2</li>
<li>List item 3</li> C. List item 1
<li>List item 4</li> D. List item 2
</ol> E. List item 3
F. List item 4
Capital Letters Special Start
Lowercase RomanNumerals
<ol type="A" start="3">
<li>List item 1</li>
i. List item 1
<li>List item 2</li> ii. List item 2
<li>List item 3</li> iii. List item 3
<li>List item 4</li> iv. List item 4
</ol>

Lowercase Roman Numerals Capital Roman Numerals

<ol type="i"> I. List item 1


<li>List item 1</li> II. List item 2
<li>List item 2</li> III. List item 3
<li>List item 3</li> IV. List item 4
<li>List item 4</li>
</ol>

47
Capital Roman Numerals Capital Roman NumeralsSpecial Start

<ol type="I"> VII. List item 1


<li>List item 1</li> VIII. List item 2
<li>List item 2</li> IX. List item 3
<li>List item 3</li> X. List item 4
<li>List item 4</li>
</ol>

Capital Roman Numerals Special Start

<ol type="I" start="7">


<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
<li>List item 4</li>
</ol>
<form method=post action="/cgi-
bin/example.cgi">
<center>
Select an option:
<select>
<option>option 1</option> Select an option: (Tip)
listbox <option selected>option 2</option> option 2
<option>
option <option>option 3</option>
<option>option 4</option>
<option>option 5</option>
<option>option 6</option>
</select><br>
</center>
</form>
This is an example displaying the use of
This is an example displaying the use of theparagraph
theparagraph tag.
tag. <p> This will create a line break and a space
between lines.
This will create a line breakand a space
Attributes: Example between lines.

1:<br> Attributes:
<br>
<p> Example 1:
<p align="left">
This is an example<br>
displaying the use<br> This is an exampledisplaying the
use
of the paragraph tag.<br>
of the paragraph tag.
<br>
paragraph
Example 2:<br>
<br> Example 2:
<p align="right"> This is an
example<br>displaying the This is an exampledisplaying the
use<br> use
of the paragraph tag.<br> of the paragraph tag.
<br>
Example 3:<br> Example 3:
<br>
<p align="center"> This is This is an exampledisplaying the use
an example<br>displaying of the paragraph tag.
the use<br>of the paragraph
tag.
small
<small> <small>Example</small> Example (Tip)
(text)
deleted
<strike> <strike>Example</strike> Example
text

48
strong
<strong> <strong>Example</strong> Example
emphasis
Example 1:

<table border="4" cellpadding="2"


cellspacing="2" width="100%">
<tr>
<td>Column 1</td>
<td>Column 2</td>
</tr>
</table>
Example 1: (Tip)
Example 2: (Internet Explorer)
Column 1 Column 2
<table border="2" bordercolor="#336699"
cellpadding="2" cellspacing="2" width="100%">
<tr>
<td>Column 1</td> Example 2: (Tip)
<td>Column 2</td>
<table> table </tr>
</table> Column 1 Column 2

Example 3:
Example 3: (Tip)
<table cellpadding="2" cellspacing="2"
width="100%">
Column 1 Column 2 Row 2
<tr>
<td bgcolor="#cccccc">Column 1</td> Row 2
<td bgcolor="#cccccc">Column 2</td>
</tr>
<tr>
<td>Row 2</td>
<td>Row 2</td>
</tr>
</table>
<table border="2" cellpadding="2"
cellspacing="2" width="100%">
<tr>
table
<td> <td>Column 1</td>
data Column 1 Column 2
<td>Column 2</td>
</tr>
</table>
<div align="center">
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th> Colum Colum Column 1 n 2
</tr> n3
table <tr> Row 2 Row 2 Row 2
<th>
header <td>Row 2</td>
Row 3 Row 3 Row 3
<td>Row 2</td>
Row 4 Row 4 Row 4
<td>Row 2</td>
</tr>
<tr>
<td>Row 3</td>
<td>Row 3</td>
<td>Row 3</td>

49
</tr>
<tr>
<td>Row 4</td>
<td>Row 4</td>
<td>Row 4</td>
</tr>
</table>
</div>
Title of your web page willbe viewable in
document
<title> <title>Title of your HTML page</title> the title bar.(Tip)
title

<table border="2" cellpadding="2"


cellspacing="2" width="100%">
<tr>
<tr> table row <td>Column 1</td> Column 1 Column 2
<td>Column 2</td>
</tr>
</table>
<tt> teletype <tt>Example</tt> Example
<u> underline <u>Example</u> Example
Example 1:<br>
Example 1:
<br>
<ul>
<li>List item 1</li>  List item 1
<li>List item 2</li>  List item 2
<ul> </ul>
<br>
unordered Example 2:<br> Example 2:
list <ul type="disc">
<li>List item 1</li>  List item 1
<li>List item 2</li>  List item 2
<ul type="circle"> o List item 3
<li>List item 3</li> o List item 4
<li>List item 4</li>
</ul>
</ul>

2.2.7 HTML iframes


HTML Iframe is used to display a nested webpage (a webpage within a webpage).
The HTML <iframe> tag defines an inline frame, hence it is also called as an Inline frame.
An HTML iframe embeds another document within the current HTML document in the rectangular
region. The webpage content and iframe contents can interact with each other using JavaScript.
Iframe Syntax

<iframe src="URL"></iframe>

2.2.7.1 Set Width and Height of iframe

You can set the width and height of iframe by using "width" and "height" attributes. By default, the
attributes values are specified in pixels, but you can also set them in percent. i.e., 50%, 60% etc.
Example: (Pixels)
<! DOCTYPE html>
<html>
<body>
<h2>HTML Iframes example</h2>
<p>Use the height and width attributes to specify the size of the iframe:</p>
<iframe src="https://www.javatpoint.com/" height="300" width="400"></iframe> </body>
</html>
50
Example: (Percentage)
<! DOCTYPE html>
<html>
<body>
<h2>HTML Iframes</h2>
<p>You can use the height and width attributes to specify the size of the iframe:</p> <iframe
src="https:// www.javatpoint.com/" height="50%" width="70%"></iframe> </body>
</html>

2.2.7.2 Using CSS to set the height and width of the iframe.

<! DOCTYPE html>


<html>
<body>
<h2>HTML Iframes</h2>
<p>Use the CSS height and width properties to specify the size of the iframe:</p>
<iframe src="https://www.javatpoint.com/" style="height:300px; width:400px"></iframe>
</body>
</html>

2.2.7.3 Remove the border of iframe

By default, an iframe contains a border around it. You can remove the border by using <style>
attribute and CSS border property.
<!DOCTYPE html>
<html>
<body>
<h2>Remove the Iframe Border</h2>
<p>This iframe example doesn't have any border</p>
<iframe src="https://www.javatpoint.com/" style="border:none;"></iframe>
</body>
</html>

2.2.7.4 Iframe Target for a link

You can set a target frame for a link by using iframe. Your specified target attribute of the link must
refer to the name attribute of the iframe.
<!DOCTYPE html>
<html>
<body>
<h2>Iframe - Target for a Link</h2>
<iframe height="300px" width="100%" src="new.html" name="iframe_a"></iframe>
<p><a href="https://www.javatpoint.com" target="iframe_a">JavaTpoint.com</a></p>
<p>The name of iframe and link target must have same value else link will not open as a frame. </p>
</body>
</html>

2.2.7.5 Embed YouTube video using iframe

You can also add a YouTube video on your webpage using the <iframe> tag. The attached video will
be played at your webpage and you can also set height, width, autoplay, and many more properties for
the video.
Following are some steps to add YouTube video on your webpage:
Goto YouTube video which you want to embed.
Click on SHARE ➦ under the video.
Click on Embed <> option.
Copy HTML code.
51
Paste the code in your HTML file
Change height, width, and other properties (as per requirement). Example:
<iframe width="550" height="315" src="https://www.youtube.com/embed/JHq3pL4cdy4"
frameborder="0 " allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-
picture" allowfullscreen style="padding:20px;"></iframe>
<iframe width="550" height="315" src="https://www.youtube.com/embed/O5hShUO6wxs" framebor
der="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-
picture" style="padding:20px;">></iframe> Attributes of <iframe>
Table 2.3 Frame Tags

Attribute name Value Description

Allowfullscreen If true then that frame can be opened in full screen.


Height Pixels It defines the height of the embedded iframe, and the default
height is 150 px.
Name text It gives the name to the iframe. The name attribute is important if
you want to create a link in one frame.
Frameborder 1 or 0 It defines whether iframe should have a border or not. (Not
supported in HTML5).
Width Pixels It defines the width of embedded frame, and default width is 300
px.
Src URL The src attribute is used to give the path name or file name which
content to be loaded into iframe.
Sandbox This attribute is used to apply extra restrictions for the content of
the frame
allow-forms It allows submission of the form if this keyword is not used then
form submission is blocked.
allow-popups It will enable popups, and if not applied then no popup will open.
allow-scripts It will enable the script to run.

allow-same- If this keyword is used then the embedded resource will be


origin treated as downloaded from the same source.

Srcdoc The srcdoc attribute is used to show the HTML (code)content in


the inline iframe. It overrides the src attribute (if a browser
supports).
Scrolling It indicates that browser should provide a scroll bar for the iframe
or not. (Not supported in HTML5)
auto Scrollbar only shows if the content of iframe is larger than its
dimensions.
yes Always shows scroll bar for the iframe.
no Never shows scrollbar for the iframe.

2.3 SVG Element:


• SVG stands for Scalable Vector Graphics.
• SVG defines vector-based graphics in XML format.
• SVG defines the graphics in XML format
52
• Every element and every attribute in SVG files can be animated
• SVG is a W3C recommendation
• SVG integrates with other W3C standards such as the DOM and XSL

<svg width="100" height="100">


<circle cx="50" cy="50" r="40" stroke="green"
stroke- width="4" fill="yellow" />
</svg>

• An SVG image begins with an <svg> element


• The width and height attributes of the <svg> element define the width and height of the
SVG image
• The <circle> element is used to draw a circle
• The cx and cy attributes define the x and y coordinates of the center of the circle. If
cx and cy are not set, the circle's center is set to (0, 0)
• The r attribute defines the radius of the circle
• The stroke and stroke-width attributes control how the outline of a shape appears.
We set the outline of the circle to a 4px green "border"
• The fill attribute refers to the color inside the circle. We set the fill color to yellow
• The closing </svg> tag closes the SVG image
2.3.1 SVG Advantages

Advantages of using SVG over other image formats (like JPEG and GIF) are:
• SVG images can be created and edited with any text editor
• SVG images can be searched, indexed, scripted, and compressed
• SVG images are scalable
• SVG images can be printed with high quality at any resolution
• SVG images are zoomable
• SVG graphics do NOT lose any quality if they are zoomed or resized
• SVG is an open standard
• SVG files are pure XML
The main competitor to SVG is Flash.
The biggest advantage SVG has over Flash is the compliance with other standards (e.g.
XSL and the DOM). Flash relies on proprietary technology that is not open source.
2.3.2 SVG Shapes
SVG has some predefined shape elements that can be used by developers:
• Rectangle <rect>
• Circle <circle>
• Ellipse <ellipse>
• Line <line>
• Polyline <polyline>
• Polygon <polygon>
• Path <path>
<!DOCTYPE html>
<html>
<body>
<svg width="300" height="200">
<polygon points="100,10 40,198 190,78 10,78 160,198"
style="fill:lime;stroke:purple;stroke-
width:5;fill-rule:evenodd;" /> Sorry, your
browser does not support inline SVG.
</svg>
53
</body>
</html>

SVG Text
<svg height="30" width="200">
<text x="0" y="15" fill="red">I
love SVG!</text> Sorry, your
browser does not support inline
SVG.
</svg>

Rotate the text:


<svg height="60" width="200">
<text x="0" y="15" fill="red" transform="rotate(30 20,40)">I love SVG</text>
</svg>
tansform=―rotate(90)‖
transform=―rotate(-90)‖
Transformation Functions
SVG provides four transformation functions: translate () rotate () scale () skew () matrix ()
Text as a Link
<svg height="30" width="200" xmlns:xlink="http://www.w3.org/1999/xlink">
<a xlink:href="https://www.w3schools.com/graphics/" target="_blank">
<text x="0" y="15" fill="red">I love SVG!</text>
</a>
Sorry, your browser does not support inline SVG.
</svg>
SVG Gradients
A gradient is a smooth transition from one color to another. In addition, several color
transitions can be applied to the same element.
There are two main types of gradients in SVG:
Linear, Radial
SVG Linear Gradient - <linearGradient>
The <linearGradient> element must be nested within a <defs> tag.
The <defs> tag is short for definitions and contains definition of special elements (such as
gradients).
Linear gradients can be defined as horizontal,
vertical or angular gradients: Horizontal gradients are
created when y1 and y2 are equal and x1 and x2 differ
Vertical gradients are created when x1 and x2 are equal
and y1 and y2 differ Angular gradients are created when
x1 and x2 differ and y1 and y2 differ
Eg. Define an ellipse with a horizontal linear gradient from yellow to red:
<svg height="150" width="400">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="200" cy="70" rx="85" ry="55" fill="url(#grad1)" />
</svg>

54
The id attribute of the <linearGradient> tag defines a unique name for the gradient
The x1, x2, y1,y2 attributes of the <linearGradient> tag define the start and end position of the
gradient
The color range for a gradient can be composed of two or more colors. Each color is specified
with a <stop> tag.
The offset attribute is used to define where the gradient
color begin and end The fill attribute links the ellipse
element to the gradient
SVG Blur Effects
<defs> and <filter>
All internet SVG filters are defined
within a <defs> element. The <defs>
element is short for definitions and
contains definition of special elements
(such as filters).
The <filter> element is used to define an SVG filter.
The <filter> element has a required id
attribute which identifies the filter. The
graphic then points to the filter to use.
The <feGaussianBlur> element is used to create blur effects:
<svg height="110" width="110">
<defs>
<filter id="f1" x="0" y="0">
<feGaussianBlur in="SourceGraphic" stdDeviation="15" />
</filter>
</defs>
<rect width="90" height="90"
stroke="green" stroke-width="3"
fill="yellow" filter="url(#f1)" />
</svg>
The in="SourceGraphic" part defines that the effect is created
for the entire element The stdDeviation attribute defines the
amount of the blur

<svg height="130" width="500">


<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
</defs>
<ellipse cx="100" cy="70" rx="85" ry="55" fill="url(#grad1)" />
<text fill="#ffffff" font-size="45" font-family="Verdana"
x="50" y="86">SVG</text> Sorry, your browser does not
support inline SVG.
</svg>

55
Table 2.4 Difference between XCanvas and SVG

Canvas SVG

Canvas draws 2D graphics, on the fly SVG is a language for describing 2D graphics
(with a JavaScript). in XML.

Resolution dependent Resolution


No support for event independent
handlers Poor text Support for
rendering capabilities event handlers
You can save the resulting image as .png Best suited for applications with large
or .jpg Well suited for graphic-intensive rendering areas (Google Maps)
games Slow rendering if complex (anything that
uses the DOM a lot will be slow)
Not suited for game applications

2.4 Cascading Style Sheets

There is no format to follow for teaching the aesthetics of style - most people, though, can
recognize something that follows a classical design. But some things can be said about the
style of a website. For instance, when Web pages belong to the same website, each page
should have a consistent look in order to provide familiarity for the user.
Style sheets (sometimes referred to as templates) are used in desktop publishing to provide
consistency when formatting text. The format applied by the stylesheet could be to
indent every first line of a paragraph by 2cm, insert a page break at the end of every
chapter, and so on. Naturally, due to multimedia, Web pages not only have to consider
text formatting, but also visual and sound presentation, and various multimedia formats in
general. Before we continue, let us briefly discuss the advantages and disadvantages of
using style sheets.

2.4.1 Advantages of Style Sheets


1. Multiple Styles - A single document can be presented in multiple styles by using multiple style
sheets.

2. Re-styling - The use of style sheets (which are separate to the HTML files) allows
the quick re- styling of any document, without modifying the original HTML.
3. Document maintenance - The ability to re-style many documents allow us to easily
make changes to the appearance of many Web pages without separately editing
each one.
4. Consistency - Style sheets guarantee consistency throughout website.

5. Optimal file size - The smaller the files the faster the download. Using style sheets
can help minimize file sizes, since, for example, every < font > tag, is defined in one
place in a style sheet, rather than in multiple places in the HTML file.

6. Style and structure - When first developed, HTML was only concerned with document
markup and not with the document's formatting. This eventually changed, with more and
56
more functionality being added to HTML to allow for formatting. With the introduction
of style sheets, the HTML document is again concerned only with structural document
markup — all formatting is now placed in the style sheet.

CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web documents.
They enforce standards and uniformity throughout a web site and provide numerous attributes to create
dynamic effects.
The advantage of a style sheet includes the ability to make global changes to all documents from a
single location. Style sheets are said to cascade when they combine to specify the appearance of a page.
2.4.2 To create an inline style
Add the style attribute to the HTML tag.
The style declaration must be enclosed within double quotation marks.
To create an embedded style
Insert a <style> tag within the head section of HTML file.
Within the <style> tag, enclose the style declarations need to the entire Web page.
The style sheet language identifies the type of style used in the document.
The default and the most common language is ―text/css‖ for use with CSS.

2.4.3 To create an External style


Create a text file containing style declarations
Create a link to that file in each page of the Web site using a <link> tag.
Specify the link attributes, such as href, rel, and type.
Link a style sheet, the value of the href attribute should be the ―URL‖ of the linked document, the value
of the rel attribute should be ―stylesheet‖ and the value of the type attribute should be ―text/css‖.
EXTERNAL.CSS:
body {background-color: gray;}
p {color: blue;}
h3{color: white;}

EXTERNAL.HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="EXTERNAL.css" /><!—Link tag for External CSS-->
</head>
<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font.
The background color of this page is gray because
we changed it with CSS! </p>
</body>
</html>

INTERNAL.HTML:
<html>
<head>
<style> <!—Style tag for Internal CSS-->
body { background-color: blue; }
p { color: white; }
</style>
</head>
<body>
57
<h2>Internal CSS</h2>
<p>This page uses internal CSS. Using the style tag we are able to modify
the appearance of HTML elements. </p>
</body>
</html>
INLINE.HTML:
<html>
<head>
</head>
<body>
<h2>InLINE CSS</h2>
<p style="color: sienna; margin-left:20px"><! —Style Attribute (INLINE)-->
This page uses INLINE CSS. Using the style ATTRIBUTE, we can modify
the appearance of HTML elements.
</p>
</body>
</html>
2.4.4 Eight CSS text properties.
Color
You can set the color of text with the following:
color: value;
Possible values are
color name – example:(red, black…)
hexadecimal number – example:(#ff0000, #000000)
RGB color code – example:(rgb(255, 0, 0), rgb(0, 0, 0))

Letter Spacing
You can adjust the space between letters in the following manner. Setting the value to 0, prevents the
text from justifying. You can use negative values.
letter-spacing: value;
Possible values are
normal
length
Example:
These letters are spaced at 5px.

Text Align
You can align text with the following:
text-align: value;
Possible values are
left
right
center
justify
Examples:
This text is aligned left.
This text is aligned in the center.
This text is aligned right.
This text is justified.
Text Decoration
You can decorate text with the following:
text-decoration: value;
58
Possible values are
none
underline
overline
line through
blink
Examples:
This text is underlined.
This text is overlined.
This text has a line through it.
This text is blinking (not in internet explorer).

Text Indent
You can indent the first line of text in an (X)HTML element with the following:
text-indent: value.
Possible values are
length
percentage
Examples:
This text is indented 10px pixels.

Text Transform
You can control the size of letters in an (X)HTML element with the following:
text-transform: value.
Possible values are
none
capitalize
lowercase
uppercase
Examples:
This First Letter In Each Word Is Capitalized, Though It Is Not In My File.
THIS TEXT IS ALL UPPERCASE, THOUGH IT IS ALL LOWERCASE IN MY FILE.
this text is all lowercase. though it is all uppercase in my file.

White Space
You can control the whitespace in an (X)HTML element with the following:
white space: value.
Possible values are
normal
pre
nowrap

Word Spacing
You can adjust the space between words in the following manner. You can use negative values.
word-spacing: value.
Possible values are
normal
length

59
Example:
These words are spaced at 5px.

2.5 The CSS Box Model


All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about
design and layout.

The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins,
borders, padding, and the actual content.

The box model allows us to add a border around elements, and to define space between elements.

The image below illustrates the box model:

Fig 2.11 Box Model

 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent

<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px.
padding: 25px.
border: 25px solid navy.
margin: 25px.
}
</style>
</head>
<body>
60
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elite, sed do eiusmod temper incididunt ut
labore et dolore magna aliquant. Ut denim ad minim veniam, quiz nostrud exercitation ullamco labor is
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui
officia deserunt mollit anim id est laborum.</div>
</body>
</html>
2.6 CSS Margin
The margin clears an area around an element (outside the border). The margin does not have a
background color, and is completely transparent.
The top, right, bottom, and left margin can be changed independently using separate properties. A
shorthand marginproperty can also be used, to change all margins at once.
Possible Values
Table 2.5 CSS Descritption

Value Description

auto The browser calculates a margin

length Specifies a margin in px, pt, cm, etc. Default value is 0px

% Specifies a margin in percent of the width of the containing element

Inherit Specifies that the margin should be inherited from the parent element

 margin: 25px 50px 75px 100px;


o top margin is 25px
o right margin is 50px
o bottom margin is 75px
o left margin is 100px
 margin: 25px 50px 75px;
o top margin is 25px
o right and left margins are 50px
o bottom margin is 75px
 margin: 25px 50px;
o top and bottom margins are 25px
o right and left margins are 50px
 margin: 25px;
o all four margins are 25px

61
2.7 Padding
The padding clears an area around the content (inside the border) of an element. The padding is
affected by the background color of the element.
The top, right, bottom, and left padding can be changed independently using separate properties. A
shorthandpadding property can also be used, to change all paddings at once.

Possible Values
Table 2.6 CSS Padding Description

Value Description

length Defines a fixed padding (in pixels, pt, em, etc.)

% Defines a padding in % of the containing element

Example:
p{
padding-top: 25px;
padding-right: 50px;
padding-bottom: 25px;
padding-left: 50px;
}

Margins and Padding


Margins means the space between the content and its neighboring content. There can be top margin,
bottom margin, left margin and right margin. The values of these properties can be given in px and in.
<!DOCTYPE html>
<html>
<head>
<style>
p
{
background-color:yellow;
}
p.margin
{
margin-top:100px.
margin-bottom:100px.
margin-right:50px.
margin-left:50px.
}
</style>
</head>

62
<body>
<p>This is a paragraph with no specified margins. </p>
<p class="margin">This is a paragraph with specified margins. </p>
</body>
</html>
This is a paragraph with no specified margins.
This is a paragraph with specified margins.
Padding means the space between the contents and its border. Various properties of padding are
padding-left, padding-right, padding-top and padding-bottom. These values can also be given in ps or
in in.
<!DOCTYPE html>
<html>
<head>
<style>
p
{
background-color:yellow;
}
p.padding
{
padding-top:25px.
padding-bottom:25px.
padding-right:50px.
padding-left:50px.
}
</style>
</head>
<body>
<p>This is a paragraph with no specified padding. </p>
<p class="padding">This is a paragraph with specified paddings. </p>
</body>
</html>
This is a paragraph with no specified padding.
This is a paragraph with specified paddings.
2.8 Class Selectors
• One or more style sheets-- Statements
• Each line in style1.css called Rule
• Form of rule called-- Rulest
• Consist of two parts
• Selector string
• Indicates the elements to which the rule should apply
• Declaration block in {}
• Specifies a value for one style property of those elements
• List of declaration separated by semicolons
• It is syntactically legal to split rules over several lines or write multiple rules on a single line
Parts of a style rule (or statement)

Fig 2.12 Parts of a style Rule


63
• Type selector: Type selector matches elements with the corresponding element type
name.
h1, h2, h3, h4, h5, h6 {background-color: purple}
• Universal selector: Every possible element type
• The universal selector matches any element type.
* {font-weight: bold}
• ID selector: Matches an element that has a specific id attribute value. Since id attributes must
have unique values, it can never match more than one element in a document.
#p1, #p3 {background-color: aqua}
<p id="P1" class="takeNote">
Paragraph with id="P1" and class="takeNote".
</p>
.
.
<p id="p3">
This paragraph (id="p3") contains a
<a href="http://www.example.net">hyperlink</a>.

2.9 Inline and Block Elements


Block-level Elements

A block-level element always starts on a new line.

A block-level element always takes up the full width available (stretches out to the left and right as far as it
can).

A block level element has a top and a bottom margin, whereas an inline element does not.

<!DOCTYPE html>
<html>
<body>
<div style="border: 1px solid black">Hello World</div>
<p>The DIV element is a block element, and will always start on a new line and take up the full width
available (stretches out to the left and right as far as it can).</p>
</body>
</html>

Inline Elements

An inline element does not start on a new line.

An inline element only takes up as much width as necessary.

64
This is a <span> element inside a paragraph.

Example
<span>Hello World</span>

2.10 Structuring pages using Semantic Tags


A semantic element clearly describes its meaning to both the browser and the developer.
Examples of non-semantic elements: <div> and <span> - Tells nothing about its content.
Examples of semantic elements: <form>, <table>, and <article> - Clearly defines its content.

2.10.1 Semantic Elements in HTML


Many web sites contain HTML code like: <div id="nav"> <div class="header"> <div
id="footer"> to indicate navigation, header, and footer.
In HTML there are some semantic elements that can be used to define different parts of a web
page:
<article>
<aside>
<details>
<figcaption>
<figure>
<footer>
<header>
<main>
<mark>
<nav>
<section>
<summary>
<time>

HTML <section> Element


The <section> element defines a section in a document.
65
According to W3C's HTML documentation: "A section is a thematic grouping of content,
typically with a heading."
Examples of where a <section> element can be used:
Chapters
Introduction
News items
Contact information
A web page could normally be split into sections for introduction, content, and contact
information.
Example
Two sections in a document:
<section>
<h1>WWF</h1>
<p>The World Wide Fund for Nature (WWF) is an international organization working on
issues regarding the conservation, research and restoration of the environment, formerly named
the World Wildlife Fund. WWF was founded in 1961.</p>
</section>
<section>
<h1>WWF's Panda symbol</h1>
<p>The Panda has become the symbol of WWF. The well-known panda logo of WWF
originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the
London Zoo in the same year of the establishment of WWF. </p>
</section>

WWF
The Worldwide Fund for Nature (WWF) is an international organization working on issues regarding
the conservation, research and restoration of the environment, formerly named the World Wildlife
Fund. WWF was founded in 1961.

WWF's Panda symbol


The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a
panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of
the establishment of WWF.

HTML <article> Element

The <article> element specifies independent, self-contained content.

An article should make sense on its own, and it should be possible to distribute it independently from the
rest of the web site.

Examples of where the <article> element can be used:

 Forum posts
 Blog posts
 User comments
 Product cards
 Newspaper articles

66
Example
Three articles with independent, self-contained content:

<article>
<h2>Google Chrome</h2>
<p>Google Chrome is a web browser developed by Google, released in 2008. Chrome is the world's most
popular web browser today! </p>
</article>

<article>
<h2>Mozilla Firefox</h2>
<p>Mozilla Firefox is an open-source web browser developed by Mozilla. Firefox has been the second most
popular web browser since January 2018. </p>
</article>

<article>
<h2>Microsoft Edge</h2>
<p>Microsoft Edge is a web browser developed by Microsoft, released in 2015. Microsoft Edge replaced
Internet Explorer. </p>
</article>

The article element


Google Chrome
Google Chrome is a web browser developed by Google, released in 2008. Chrome is the world's most
popular web browser today!

Mozilla Firefox
Mozilla Firefox is an open-source web browser developed by Mozilla. Firefox has been the second
most popular web browser since January 2018.

Microsoft Edge

Microsoft Edge is a web browser developed by Microsoft, released in 2015. Microsoft Edge replaced
Internet Explorer.

HTML <header> Element

The <header> element represents a container for introductory content or a set of navigational links.

A <header> element typically contains:

 one or more heading elements (<h1> - <h6>)


 logo or icon
 authorship information

Note: You can have several <header> elements in one HTML document. However, <header> cannot be
placed within a <footer>, <address> or another <header> element.
67
Example

A header for an <article>:


<article>
<header>
<h1>What Does WWF Do? </h1>
<p>WWF's mission:</p>
</header>
<p>WWF's mission is to stop the degradation of our planet's natural environment,
and build a future in which humans live in harmony with nature.</p>
</article>
HTML <footer> Element

The <footer> element defines a footer for a document or section.

A <footer> element typically contains:

 authorship information
 copyright information
 contact information
 sitemap
 back to top links
 related documents

You can have several <footer> elements in one document.

Example
A footer section in a document:

<footer>
<p>Author: Hege Refsnes</p>
<p><a href="mailto:[email protected]">[email protected]</a></p>
</footer>

HTML <nav> Element

The <nav> element defines a set of navigation links.

Notice that NOT all links of a document should be inside a <nav> element. The <nav> element is
intended only for major block of navigation links.

Browsers, such as screen readers for disabled users, can use this element to determine whether to omit
the initial rendering of this content.
Example
A set of navigation links:

<nav>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
68
<a href="/js/">JavaScript</a> |
<a href="/jquery/">jQuery</a>
</nav>

HTML <aside> Element

The <aside> element defines some content aside from the content it is placed in (like a sidebar).

The <aside> content should be indirectly related to the surrounding content.

Example
Display some content aside from the content it is placed in:

<p>My family and I visited The Epcot center this summer. The weather was nice, and Epcot was
amazing! I had a great summer together with my family! </p>

<aside>
<h4>Epcot Center</h4>
<p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international
pavilions, award-winning fireworks and seasonal special events.</p>
</aside>
HTML <figure> and <figcaption> Elements

The <figure> tag specifies self-contained content, like illustrations, diagrams,


photos, code listings, etc.

The <figcaption> tag defines a caption for a <figure> element.


The <figcaption> element can be placed as the first or as the last child of
a <figure> element.

The <img> element defines the actual image/illustration.

<figure>

<img src="pic_trulli.jpg" alt="Trulli">

<figcaption>Fig1. - Trulli, Puglia, Italy.</figcaption>

</figure>

Table 2.8 Article Element

Tag Description

<article> Defines independent, self-contained content

69
<aside> Defines content aside from the page content

<details> Defines additional details that the user can view or hide

<figcaption> Defines a caption for a <figure> element

<figure> Specifies self-contained content, like illustrations, diagrams,


photos, code listings, etc.

<footer> Defines a footer for a document or section

<header> Specifies a header for a document or section

<main> Specifies the main content of a document

<mark> Defines marked/highlighted text

<nav> Defines navigation links

<section> Defines a section in a document

<summary> Defines a visible heading for a <details> element

<time> Defines a date/time

SUMMARY
 Tables are defined with the <table> tag.
 Constructing an HTML table consists of describing the table between the beginning table tag,
<TABLE>, and the ending table tag, </TABLE>.
 Links are the essence of HTML — they are what makes it unique. Links are defined with the
<a> tag.
 If you do not specify a border attribute the table will be displayed without any borders.
70
 <Img> causes an ―inline image‖ to be inserted into the output.
 Image maps are images with clickable areas (sometimes referred to as ―hotspots‖) that usually
link to another page.
 Email links are done much the same as links to other pages, using the <a href> tag.
 The key difference between an inline image and an image retrieved with the <a> tag is that an
inline image requires no action on the part of the reader.
 Analyzing CSS Stylesheets with different formats.
 Concept of CSS Pseudo selectors
Keywords
alt: alt is used to provide an text alternative to the image for readers whose browsers do not
support graphics.
Cell tags: <TD> </TD>
Image links: Image links are constructed as you might expect, by embedding an <img> tag
inside of an anchor element <a>.
Links: Links are the essence of HTML — they are what makes it unique
Row tags: <TR> </TR>
src: The src attribute is used to specify the URL of the image.
Table tags: <TABLE> </TABLE>
Table: Tables are defined with the <table> tag.
CSS: The cascading style is many times defined in a separate file. This file is called CSS file.
In CSS file one or more style rules are given.

External Style Sheets: They enable you to change the appearance and layoutof all the pages
in a Web site, just by editing one single file!
CSS Selectors: They allow you to select and manipulate HTML element(s).
Class Selector: They find elements with the specific class.
SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What is meant by HTML?
2. What are the two different types of tags?
3. What is the purpose of using frames in HTML?
4. What is an image map?
5. Write a short note on use of CSS.
6. What is the difference between external and internal style sheet?
Long Answer Questions
1.Discuss the various features available in HTML to format the text with example.
2. Explain how tables can be inserted into HTML document with example.
71
3. Explain in detail about Cascading Style Sheets with suitable examples.
4. Explain any eight CSS text properties.
5. Explain how to use CSS to control the style and layout of multiple web pages.
6. What is text color property in CSS? Write a code of CSS to change background color of web
page ―GREEN‖.
7.. Explain the concept of Margins and padding with examples.
8.Write short notes on inline and block elements.
9. Explain the structuring pages using Semantic Tags.
FURTHER READINGS
Harvey & Paul Deitel& Associates, Harvey Deitel and Abbey Deitel, ―Internet and World Wide
Web - How to Program‖, Fifth Edition, Pearson Education, 2011.
1. Keith J. Grant, ―CSS in Depth‖, Manning Publications,1 st edition,2018

72
UNIT III – WEB PAGE LAYOUTS WITH CSS3

CONTENTS
Learning Objectives Learning
OutcomesOverview
3.1 CSS-Definition
3.2 Classfication of CSS
3.3 Structure of CSS
3.4 CSS Positioning
3.5 CSS floats and z-index
3.6 Layouts with Flexbox

3.7 Responsive web Design with media queries

3.8 Advanced CSS Effects

3.9 Gradients opacity, box shadow

3.10 CSS Animations

3.11 CSS Framework

3.12 Bootstrap

Summary
Keywords
Self-Assessment QuestionsFurther

3.1 Cascading Style Sheet (CSS)


Definition
Cascading Style Sheet (CSS) is used to set the style in web pages that contain HTML elements. It sets
the background color, font-size, font-family, color, … etc property of elements on a web

CSS are powerful mechanism for adding styles (e.g. Fonts, Colors, Spacing) to web documents.
They enforce standards and uniformity throughout a web site and provide numerous attributes to create
dynamic effects.
The advantage of a style sheet includes the ability to make global changes to all documents from a
single location. Style sheets are said to cascade when they combine to specify the appearance of a page.

3.2 Classification of CSS


There are three types of CSS which are given below:

Inline CSS
Internal or Embedded CSS
External CSS
73
Inline CSS: Inline CSS contains the CSS property in the body section attached with element is known
as inline CSS. This kind of style is specified within an HTML tag using the style attribute.
Example:

<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>

<body>
<p style = "color:#009900; font-size:50px;
font-style:italic; text-align:center;">
Welcome to web design
</p>

</body>
</html>
Output:

Fig:-3.1 Output of inline CSS


Internal or Embedded CSS:
This can be used when a single HTML document must be styled uniquely. The CSS rule set should
be within the HTML file in the head section i.e the CSS is embedded within the HTML file.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
74
.geeks {
font-style:bold;
font-size:20px;
}
</style>
</head>
<body>
<div class = "main">
<div class ="GFG">welcome to web design</div>

<div class ="geeks">


A computer science subject for distance
</div>
</div>
</body>
</html>
Output:

Fig:-3.2 Output of internal CSS

External CSS:
External CSS contains separate CSS file which contains only style property with the help of tag
attributes (For example class, id, heading, … etc). CSS property written in a separate file with
.css extension and should be linked to the HTML document using link tag. This means that for
each element, style can be set only once and that will be applied across web pages.
Example: The file given below contains CSS property. This file save with .css extension.
For Ex: web.css

body {
75
background-color:powderblue;
}
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
#geeks {
font-style:bold;
font-size:20px;
}
Below is the HTML file that is making use of the created external style sheet

link tag is used to link the external style sheet with the html webpage.
href attribute is used to specify the location of the external style sheet file.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="geeks.css"/>
</head>

<body>
<div class = "main">
<div class ="GFG">web design</div>
<div id ="geeks">
computer science for distance
</div>
</div>
</body>
</html>

76
3.3. CSS Strucuture
A Cascading Style Sheet (CSS) rule is a statement that defines the style of one or more elements in
your web page. These rules follow a specific structure. The format or syntax for CSS rules
consists of a selector and a declaration. A declaration block consists of several declarations for s
given selector.

3.4 CSS Positioning

The CSS positioning properties allow you to position an element. It can also place an element
behind another, and specify what should happen when an element's content is too big.
Elements can be positioned using the top, bottom, left, and right properties. However, these
properties will not work unless the position property is set first. They also work differently
depending on the positioning method.
There are four different positioning methods.
Static Positioning
HTML elements are positioned static by default. A static positioned element is always positioned
according to the normal flow of the page.
Static positioned elements are not affected by the top, bottom, left, and right properties.
Fixed Positioning
An element with fixed position is positioned relative to the browser window.
It will not move even if the window is scrolled:
Example
p.pos_fixed
{
position:fixed;
top:30px;
right:5px;
}
Note: IE7 and IE8 support the fixed value only if a! DOCTYPE is specified.
Fixed positioned elements are removed from the normal flow. The document and other elements
behave like the fixed positioned element does not exist.
Fixed positioned elements can overlap other elements.
Relative Positioning
A relative positioned element is positioned relative to its normal position.
Example
h2.pos_left
{

77
position: relative;
left: -20px;
}
h2.pos_right
{
position: relative;
left:20px;
}
The content of relatively positioned elements can be moved and overlap other elements, but the
reserved space for the element is still preserved in the normal flow.
Example
h2.pos_top
{
position: relative;
top: -50px;
}
Relatively positioned elements are often used as container blocks for absolutely positioned
elements.
Absolute Positioning
An absolute position element is positioned relative to the first parent element that has a position
other than static. If no such element is found, the containing block is <html>:
Example
h2
{
position: absolute;
left:100px;
top:150px;
}
Absolutely positioned elements are removed from the normal flow. The document and other
elements behave like the absolutely positioned element does not exist.
Absolutely positioned elements can overlap other elements.
Overlapping Elements
When elements are positioned outside the normal flow, they can overlap other elements.
The z-index property specifies the stack order of an element (which element should be placed in
front of, or behind, the others).
An element can have a positive or negative stack order:
78
Example
img
{
position: absolute;
left:0px;
top:0px.
z-index: -1;
}
An element with greater stack order is always in front of an element with a lower stack order.

3.5 CSS floats and z-index

CSS Float
The float property enables you to take an element out of normal flow and put content side-by-side.
Elements are floated horizontally, that means, an element can only be floated left or right only.

sidebox {

float: right.

width: 250px.

Float property accepts keyword values left and right float elements those directions respectively and set
to none for not floated. When you set the float property for an element, you should specify the width
and height otherwise its sizing becomes shrink-to-fit horizontally and vertically.

Consider the following example:

<! Doctype>
<html>
<head>
<style>
. box1 {
background: #DDF.
height: 100px.
width:100px.
}
. box2 {

79
background: #4FFFA1.
height: 100px.
width:100px.
}
</style>
</head>
<body>
<div class="box1">
Box1
</div>
<div class="box2">
Box2
</div>
</body>
</html>
When you run this code on browser you will get the following output:

Fig:-3.3 Output of float property

In the above picture the boxes are not set the float property.

Now we set the float property to both boxes as float: left.

box1 {
float: left;
background: #DDF.
height: 100px.
width:100px.
}
. box2 {
float: left;
background: #4FFFA1.

80
height: 100px.
width:100px.
}
In the above code we set float property to each box as float: left;

Now you can see the boxes floated from left to right.

Fig:-3.4 Output of float property after set

Again we set first box as float: left and second box as float: right;
.box1 {
float:left;
background: #DDF.
height: 100px.
width:100px.
}
. box2 {
float:right;
background: #4FFFA1.
height: 100px.
width:100px.
}
Output

Fig:-3.5 Output of float property


81
Now you can see first box is floted to left and second one is floated to right.
z-index
While overlapping CSS elements, when using absolute and relative position, the default behavior is to
have the first elements underneath later ones. In these cases, we can control layering of positioned
elements by using the z-index property. When using the z-index property you can specify which of the
boxes appears on top the other one.

<!Doctype>
<html>
<head>
<style>
div {
width:100px.
height:100px.
}
div.box1 {
background: #dad7d7.
position:relative;
z-index:1;
}
div.box2 {
background: #ffe7bc.
position: relative;
top: -80px.
left:50px.
z-index:2.
}
</style>
</head>
<body>
<div class="box1"> BOX - 1 </div>
<div class="box2"> BOX - 2 </div>
</body>
</html>

82
output

Fig:-3.6 Output of Z-Index

Now you can see the BOX-1 is behind the BOX-2, because z-index of BOX-1 is 1 and BOX-2 is 2.
Now we are going to change the z-index order as BOX-1 is 2 and BOX-2 is 1.
div {
width:100px;
height:100px;
}
div.box1 {
background: #dad7d7.
position: relative;
z-index:2;
}
div.box2 {
background: #ffe7bc.
position:relative;
top: -80px;
left:50px.
z-index:1.
}
output

Fig:-3.7 Output of Z-index

Now you can see BOX-1 come in front and BOX-2 going behind the BOX-1.
83
It is noted that z-index works on positioned elements only like position: absolute, position: relative and
position: fixed.
3.6 Layouts with Flexbox

The Flexible Box Module is a layout method that distributes space along a single row or column.
Unlike other layout methods, flexbox provides an efficient way to flexibly(properly) layout, align
and distribute space among items in a container.

Basic Terminologies

In order to understand flexbox, we should first talk about some terminologies

Flex container: According to MDN, a flex container is an area of a document laid out using flexbox.
This is the parent element which holds the children‘s elements. It could be a div, ul etc.

Flex item: A flex item is a child within the flex container.

Main axis: The main axis of a flex container is defined as the direction in which the flex items are
laid out.

Cross axis: The cross axis is the axis perpendicular to the main axis. For example, if the flex-
direction of your container is set to row, that is items are positioned horizontally, then the cross axis
will run along the column and vice versa.

the figure below helps you understand the terminologies better.

Fig:-3.8 Output of flex container

Flexbox in Action

Now that you know the basics of flexbox, let's see it in action. The first thing to do when using flexbox is
to define the flex container. To do this, you set the property display: flex on the parent container.

The HTML below holds a container div (parent element) and other divs(child elements). We will use this
to explain CSS flexbox in details.
84
<div class="container">
<div></div>
<div></div>
<div></div>
</div>
To see flexbox in action, add the property display: flex.

container {
display: flex;
}

Add some style to the children divs

container > div {


background-color: maroon;
min-height: 100px;
margin: 10px;
width: 100px;
}

This is what the output should look like.

Fig:-3.9 Output of container

By setting the property display: flex on the parent div, you immediately make the parent element a
flex container and the children elements the flex items.

As you may or may not have known, div is a block element and you may have expected the output to
be something like this.

Fig:-3.10 Output of property display

Well by default, flexbox makes the flex items inline elements automagically which makes the flex
items stack horizontally instead of vertically. You can decide to make the flex items stack vertically
85
or in a reverse direction by adding a property called flex-direction

Flex Container Properties


Flex container has some properties that enable you style flex items however you want. The flex
container properties are explained below.

1. Flex-direction: The flex-direction property controls the direction of the flex items. It allows you to
change the direction of the flex items.

The flex-direction property takes in any of the four values: row, row-reverse, column, column-
reverse. These properties allow you to align the flex items horizontally(main-axis) or
vertically(cross-axis).

By default, the flex-direction property is set to row. This is why the first image of the container
element laid all flex items horizontally from left to right.

Let's change the flex-direction property to column and see what happens.

container {
display: flex.
flex-direction: column
}

This is the output

Fig:-3.11 Output of flex container


The value of the flex-direction property allowed us to change the direction of the flex items hence
allowing the items to flow from top to bottom.

Note that by setting the flex-direction property to column, the main axis runs along the vertical axis
while the cross axis runs along the horizontal axis.

See the image below

Fig:-3.11 Output of flex-direction

86
Flex-wrap:

Flex-wrap property allows flex items to fit on multiple lines. By default, the flex-wrap property
is set to nowrap which means that the flex items are set to fit on one line only.

When the flex-wrap property is set to nowrap, flex items no matter the number will shrink to ensure
they fit on one line.

Let me explain further with an example. I'll add five more divs to the parent element.
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>

container {
display: flex;
}

Output

Fig:-3.12 Output of flex property


You'll notice that the items had to shrink to fit on one line.

Let's now set flex-wrap property to wrap


container {
flex-wrap: wrap
}

See output below

Fig:-3.13 Output of flex wrap property


87
Justify-content: The justify-content property align items on the main axis in the
container. Justify-content property uses any of these values: flex-start, flex-end, center,
space-around, space-between, space-evenly.

- Flex-start: Flex-start lines up all flex items from the start of the container. By default,
the justify-content property is set to flex-start. This is why all flex items are stacked
horizontally from left to right.

<div class="container">

<div></div>

<div></div>

<div></div>

</div>

container {

display: flex.

justify-content: flex-start.

The output will look like this:

Fig:-3.14 Output of Justify Content


Flex-end: Flex-end lines up all flex items to the end of the container.

container {

justify-content: flex-end.

Fig:-3.15 Output of Justify Content

88
Center: Center aligns all flex items to the center of the container.

Fig:-3.15 Output of center all flex items

Space-evenly: Space-evenly distributes space evenly around each item in the container.

.container {

Justify-content: space-evenly;

Fig:-3.16 Output of Justify Content

3.7 Responsive web Design with media queries

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

Example

If the browser window is 600px or smaller, the background color will be light blue:

<! DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>

body {

background-color: lightgreen;

89
@media only screen and (max-width: 600px) {

body {

background-color: lightblue;

</style>

</head>

<body>

<p>Resize the browser window. When the width of this document is 600 pixels or less, the background-
color is "lightblue", otherwise it is "lightgreen".</p>

</body>

</html>

Breakpoint

Media queries can help with that. We can add a breakpoint where certain parts of the design will behave

90
differently on each side of the breakpoint.

<!DOCTYPE html>

<html>

<head>

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>

*{

box-sizing: border-box.

. row::after {

content: "";

clear: both.

display: block.

[class*="col-"] {

float: left.

padding: 15px.

html {

font-family: "Lucida Sans", sans-serif;

.header {

background-color: #9933cc.

color: #ffffff.

padding: 15px.

. menu ul {

list-style-type: none.

91
margin: 0;

padding: 0;

. menu li {

padding: 8px.

margin-bottom: 7px.

background-color: #33b5e5.

color: #ffffff.

box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);

.menu li:hover {

background-color: #0099cc;

.aside {

background-color: #33b5e5.

padding: 15px.

color: #ffffff.

text-align center.

font-size: 14px.

box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);

. footer {

background-color: #0099cc.

color: #ffffff.

text-align: center.

font-size: 12px.

padding: 15px.

/* For desktop: */

92
.col-1 {width: 8.33%;}

.col-2 {width: 16.66%;}

.col-3 {width: 25%;}

.col-4 {width: 33.33%;}

.col-5 {width: 41.66%;}

.col-6 {width: 50%;}

.col-7 {width: 58.33%;}

.col-8 {width: 66.66%;}

.col-9 {width: 75%;}

.col-10 {width: 83.33%;}

.col-11 {width: 91.66%;}

.col-12 {width: 100%;}

@media only screen and (max-width: 768px) {

/* For mobile phones: */

[class*="col-"] {

width: 100%.

</style>

</head>

<body>

<div class="header">

<h1>Chania</h1>

</div>

<div class="row">

<div class="col-3 menu">

<ul>

<li>The Flight</li>

<li>The City</li>

93
<li>The Island</li>

<li>The Food</li>

</ul>

</div>

<div class="col-6">

<h1>The City</h1>

<p>Chania is the capital of the Chania region on the island of Crete. The city can be divided in two
parts, the old town and the modern city. </p>

</div>

<div class="col-3 right">

<div class="aside">

<h2>What? </h2>

<p>Chania is a city on the island of Crete. </p>

<h2>Where? </h2>

<p>Crete is a Greek island in the Mediterranean Sea.</p>

<h2>How? </h2>

<p>You can reach Chania airport from all over Europe. </p>

</div>

</div>

</div>

<div class="footer">

<p>Resize the browser window to see how the content respond to the resizing.</p>

</div>

</body>

</html>

94
Fig:-3.17 Output of media queries

Fig:-3.18 Output of media

3.8 Advanced CSS Effects


CSS Minify

Minification (minify) refers to the process of removing unnecessary data like comments, unused codes,
changing longer variables and function names to shorter ones, and many more without affecting your code
display on browsers.

There are multiple sources available online to minify the CSS file. You can use them to reduce the size of the
CSS file.

CSS Loader

A loader is an animation that shows the visitor about the page when it is loading. It is helpful when a page
takes some seconds to load the webpage content.

CSS User Interface

The CSS user interface is a module that lets you define the rendering and functionality of features to the user

95
interface. Here you will discuss the following user interface property:

Resize

Resize Property

The resize property specifies whether an element should be resizable by the user.

<! DOCTYPE html>

<html>

<head>

<style>

Div{

Border:3px solid.

Padding: 50px,50px.

Width: both;

Overflow: auto;

Font-size:34px.

Body {

Font-size:34px.

</style>

</head>

<body>

<p><b>Note:</b>Internet Explorer and opera do not support the resize property</P>

<div> Let the user resize the box</div>

</body>

96
Fig:-3.19 Output of Resize the box
Outline-offset

The outline-offset CSS property sets and determines the space between an outline and the edge or border of
an element.

3.9 Gradient’s opacity, box shadow


Gradient

Using the background property, we can also supply gradient tones. This is done by providing position or
angle information for where the first color starts, followed by the color stop value, then optionally
followed by a percent of space within the element that color stop should take up. There are three types
of color gradients linear-gradient, radial-gradient, and repeating: repeating-linear-gradient and
repeating-radial-gradient. Below is an example of a linear gradient.

div {

background: -moz-linear-gradient (left, rgba(94,250,255,1) 0%, rgba(3,22,237,1) 100%);

background: -webkit-gradient (left top, right top, color-


stop(0%, rgba(94,250,255,1)), color-stop(100%,
rgba(3,22,237,1)));

background: -webkit-linear-gradient (left,


rgba(94,250,255,1) 0%, rgba(3,22,237,1) 100%);

background: -o-linear-gradient (left, rgba(94,250,255,1)


0%, rgba(3,22,237,1) 100%);

background: -ms-linear-gradient (left, rgba(94,250,255,1)


0%, rgba(3,22,237,1) 100%);

background: linear-gradient (to right, rgba(94,250,255,1)


0%, rgba(3,22,237,1) 100%);

97
filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#5efaff', endColorstr='#0316ed',
GradientType=1 );

Fig:-3.20 Output of Gradient


We can specify a background image, color, or gradient on elements using the background property.

Opacity
Opacity allows us to add transparency to our elements. The standard opacity property uses vlaues 0 to
1, with 0 being completely transparent and 1 being completely opaque. 0.5 for example, is the
equivalent of 50% opacity.

Note: it is important to understand that opacity not only adjusts the background but also any content or
child elements within the selected element. So text inside an element would also have opacity effecting it.
If you were just trying to make the background color transparent, but not the text then it would be more
ideal then to use rgba value such as background: rgba(255,0,0,0.5) This for example would create a 50%
transparent red background leaving the content and child elements within it unaffected.

div {

filter: alpha(opacity=50); /*IE*/

-moz-opacity: 0.5; /*FF 0.9*/

-khtml-opacity: 0.5; /*Safari 1.x*/

opacity: 0.5;}

Fig:-3.21 Output of opacity

3.10 CSS Animations

Animation can bring creativity, enthusiasm, grab the user‘s attention, convey things quickly, and
improve usability. Recently, there has been a rise in the use of animation on websites and web apps.
CSS Animations are an excellent way to create visual animations that are not restricted to a single

98
motion like CSS Transitions but are far more developed. With that thought in mind, CSS developers
thought of introducing them to their library as CSS Animations.

Indeed, we can build some stunning animations using JavaScript and jQuery, but this is an expensive
approach. For example, processing speed, cross browser compatibility, and code complexity are
considered when designing animated UI.

Moving the animations to CSS provides better performance than JavaScript as the browser takes control
and optimizes the animation for the performance. The properties that come with the CSS animations can
be divided into three major categories:

Transformation – Transforming the dimensions, rescaling the objects, moving them from point A to B,
etc.

Transitions – Performing the transformations smoothly.

Keyframes – Changing the animation (property, value, etc.) at a given time or state.

The transform property in CSS animation makes transformations to the size (rescaling), moving them
(translating), rotating them (rotations) or skewing them on the web page. The CSS transform requires four
types of values:

none: To define that no transformation is intended on the object.

value: To assign a value such as rotate.

inherit: Inherit the property from the parent element.

initial: Set the value as the default value for the property
assigned to the object.

The ―value‖ part defined in the above pointer determines


what we want to do with the object.

You can replace the value with one of the four options:

Translate

The ―translate‖ value is used to move the object from point A to point B. The translation can happen either
on the X-axis or the Y-axis.

Syntax:

transform: translate option(values); Here are the translate options are as follows provide by CSS
animations:

translate(value): To translate only along the X-axis.

complete css animation

translate (value, value): To translate along the X and Y axis.


99
translateX(value): To translate along the X axis.

translateY(value): To translate along the Y axis.

<html lang="en" dir="ltr">

<head>

<meta charset="utf-8">

<title>Flexbox demo</title>

<style>

.transform_animation {

width: 200px.

height: 100px.

margin-top:200px.

background-color: rgb(235, 122, 84);

.transform_animation:hover {

transform: translate (100px, 100px);

</style>

</head>

<body>

<br>

<center>

<div class = "transform_animation">

</div>

</center>

</body>

</html>

100
Fig:-3.22 Output of CSS animations
CSS Animations – Transitions

In the above section about the transformations in CSS Animations, we achieved the required goal
(such as scaling the dimensions and moving objects) but the transition from the starting state to the
end state is abrupt as shown in the below image.

The transition-property attribute specifies what property needs to apply to the transition. For example,
transition-property: width will apply the transitions when there is a change in the width of the elements.

It is important to note that not all properties can be animated and applied in the transition-property
section. CSS provides a list of animatable properties, and they keep on changing with every version of
CSS. Therefore, it is important to check your property in CSS Animations and perform cross browser
testing from time to time.

Also, a special case occurs in ―transition-property‖ when the developer uses a shorthand property as a
value. For example, transition-property: background is one such property. Here, the background is a
shorthand for multiple attributes and sub-properties of background. When such a shorthand is used, the
animation is applied to all the sub-properties which are under the segment.

The transition-property takes the following values:

none: To signify that no property should make transitions.

all: To signify all the properties that can transit or should


transit.

property name: The name of the property that you want the
transition to take place.

101
Syntax:

transition-property: property_name.

<html lang="en" dir="ltr">

<head>

<meta charset="utf-8">

<title>Flexbox demo</title>

<style>

.transform_animation {

width: 200px.

height: 100px.

margin-top:200px.

background-color: rgb(235, 122, 84);

.transform_animation:hover {

transform: skew(30deg, 30deg);

transition-duration: 2s;

</style>

</head>

<body>

<br>

<center>

<div class = "transform_animation">

</div>

</center>

</body>

</html>

102
Fig:-3.14 Output of transform animation

3.11 CSS Framework

The previous chapters have covered how to use CSS to make your page both stylish and responsive.
While it is certain possible to implement an entire site by creating your own CSS rules, that can quickly
get tedious: often you‘d like a page to have a ―standard‖ set of rules (because the browser‘s style-less
appearance) and then customize those rules to your liking.

For this reason, most professional web developers utilize an existing CSS Framework instead. A CSS
Framework is a stylesheet (a .CSS file!) that contains a large list of pre-defined rules that you can
apply to your page. CSS frameworks provide a few benefits:

Applies attractive default styling to all HTML elements: CSS frameworks make your pages
instantly look better through a bunch of element selector rules. Frameworks provide pleasant default
fonts, line spacing, spacing, and link styling without any extra effort on your part.

Provides style classes for common UI components: framework stylesheets will also include CSS
classes you can add to your markup to easily include badges, in-page tabs, drop-down buttons,
multi-column layouts, and more. Frameworks enable you to add style your page by specifying CSS
classes, rather than needing to define multiple CSS rules for a single effect.

CSS frameworks are thus designed to make your life easier and your development more efficient—
while still enabling you to provide your own customizations and styling with all the power of CSS.

There are many different CSS frameworks to choose from. Some popular ones include:

Bootstrap is the most used CSS framework on the web. Sometimes called ―Twitter Bootstrap‖, it
was originally created at Twitter to enforce some consistency among their internal tools but was
released as an open-source project in 2011. Its popularity has benefits and drawbacks: it‘s very well

103
tested, documented, and supported, but it‘s also so prevalent that it‘s default look has become
cliché.

The latest release of Bootstrap, v4 was released in 2017. This version includes an update look and
feel and makes it relatively easy to create your own customized version. Bootstrap 4 also uses
Flexbox as a foundation for its grid system, offering some better performance. For this and other
reasons, Bootstrap 4 does not support IE 9 or earlier browsers. For older browsers, you‘d want to use
Bootstrap 3.

This text discusses Bootstrap 4 as an example. Be careful that you are looking at information about the
right version if you seek out documentation or help online!

Foundation is Bootstrap‘s chief rival and has a reputation for being more ahead-of-the-curve than
Bootstrap (introducing new features sooner). For example, it was the first framework to use a
responsive mobile-first design and provided a Flexbox-based grid long before Bootstrap. Foundation
has most of the same UI elements as Bootstrap, but with a different look and feel (that can be
customized through a web-based tool).

Material Components for the Web (MCW) is an official implementation of Google‘s Material Design
visual language. This is the look-and-feel found in most Google products and Android applications.
Material Design is very opinionated, so MCW is very difficult to customize. The MCW style class
names are also very verbose, as they follow the Block, Element, Modifier (BEM) naming scheme.

Materialize is the other popular Material Design implementation. This is an open-source project, so it
is not provided nor supported by Google. However, it is structurally like Bootstrap, making it easy to
learn and popular among people who know that framework.

normalize.css is not so much a full framework as a small utility that performs browser normalization
(also called a ―reset‖). normalize.css standardizes the quirks across browsers and making it so that the
same HTML and CSS is displayed more consistently and without errors. Note that most other
frameworks include some version of this package (for example, Bootstrap contains a fork called
Reboot).

3.12 Bootstrap
This section discusses some of the features and uses of the Bootstrap CSS framework. Note that many

104
other frameworks are used in a similar fashion (though the specific classes and components may be
different).

You include the Bootstrap framework by linking its .CSS file to your page (whether from a CDN or a
local file). You can get the link for the latest version from the Bootstrap Home Page.

<link rel="stylesheet"

href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"

integrity="sha384-
9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4"

crossorigin="anonymous">

(This <link> example has 2 additional (optional) attributes: integrity gives a cryptographic hash of the
source code so the browser can make sure you didn‘t download a malicious file by mistake, and cross
origin which says that no credentials are sent to the remote server—When you first include the
Bootstrap framework, you‘ll immediately see the effects (usually for the better!): the default font has
changed, margins are different, and so forth. The Bootstrap CSS file contains several rules that apply to
elements without an extra work, including the <body> and headers. See the documentation for details
about the default styling (as well as the entire ―Content‖ section of the documentation).

SUMMARY
 To learn about CSS Positioning
 To learn about CSS floats and z-index
 Discuss Responsive Web Design with media queries
 To learn the concepts of Advanced CSS Effects, Gradient‘s opacity, box shadow, CSS
Animations

KEYWORDS
Positioning: The CSS positioning properties allow you to position an element.

CSS Float: The float property enables you to take an element out of normal flow and put content side-
by-side. Elements are floated horizontally, that means, an element can only be floated left or right only.

z-index: While overlapping CSS elements, when using absolute and relative position, the default
behaviour is to have the first elements underneath later ones. In these cases, we can control layering of
positioned elements by using the z-index property. When using the z-index property you can specify
which of the boxes appears on top the other one.

Flex container: According to MDN, a flex container is an area of a document laid out using flexbox.
This is the parent element which holds the children‘s elements. It could be a div, ul etc.

Flex item: A flex item is a child within the flex container.


105
Main axis: The main axis of a flex container is defined as the direction in which the flex items are laid
out.

Cross axis: The cross axis is the axis perpendicular to the main axis. For example, if the flex-direction
of your container is set to row, that is items are positioned horizontally, then the cross axis will run
along the column and vice versa.

Gradient: We can specify a background image, colour, or gradient on elements using the background
property.

Opacity: Opacity allows us to add transparency to our elements. The standard opacity property uses
values 0 to 1, with 0 being completely transparent and 1 being completely opaque. 0.5 for example, is
the equivalent of 50% opacity.

SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What do you mean Positioning?
2. What is called Z-index?
3. Write short notes on media quires.
4. What is meant by Gradients?
5. What is meant by opacity?
6. What is meant by Bootstrap?
Long Answer Questions
1. Explain the concepts of positioning in CSS.
2. Discuss in Detail Layouts with Flexbox.
3. Explain the advanced CSS Effects.
4. Explain the CSS Animations with examples.
5. Explain the concepts of CSS Frameworks with example.
FURTHER READINGS
1. Harvey & Paul Deitel & Associates, Harvey Deitel and Abbey Deitel, ―Internet and World
Wide Web - How to Program‖, Fifth Edition, Pearson Education, 2011.
2. Keith J. Grant, ―CSS in Depth‖, Manning Publications,1 st edition,2018.
3. Elizabeth Catrol, ―HTML5 & CSS3 Visual Quick Start Guide‖, Peachpit Press. 7th Edition
2012
4. https://www.codementor.io/

106
UNIT 4 - JAVASCRIPT

CONTENTS
Learning Objectives

Learning OutcomesOverview

4.1 Basics of JavaScript


4.2 JavaScript Objects
4.3 JSON
4.4 Understanding the DOM

4.5 JavaScript Events and Input Validation.

4.6 Modifying CSS Elements using JavaScript.

4.7 JavaScript Local Storage

4.8 Ajax.

4.9 Jquery Selectors

4.10 Adding and Removing Elements with Jquery.

4.11 Ajax with Jquery.

4.12 Animation with Jquery

Summary Keywords
Self-Assessment QuestionsFurther
Readings

LEARNING OBJECTIVES
After studying this lesson, you should be able to:
 Illustrate JavaScript concepts
 Learn about JSON
 Learn the concepts of AJAX
 Learn about JQuery

LEARNING OUTCOMES
Upon completion of the lesson, students are able to demonstrate a goodunderstanding of:
 concept of JavaScript
 explain JSON and AJAX Concepts.
 Explain the concepts of Jquery

107
4.1 Basics of JavaScript
Java script is a browser-interpreted language that was created to access all elements of HTML and the
browser. The processing is done entirely by the client-side browser which makes it very useful tool to
handle processing which would have otherwise been checked server-side, thereby reducing overhead.
Java script is also used to increase user interaction, animate objects, create drop down navigation,
grab data from databases, and more!
JavaScript is a programming language that can be included on web pages to make them more
interactive. You can use it to check or modify the contents of forms, change images, open new
windows, and write dynamic page content. You can even use it with CSS to make DHTML (Dynamic
Hypertext Markup Language). This allows you to make parts of your web pages appear or disappear
or move around on the page. JavaScript‘s only execute on the page(s) that are on your browser
window at any set time. When the user stops viewing that page, any scripts that were running on it are
immediately stopped. The only exceptions are cookies or various client-side storage APIs, which can
be used by many pages to store and pass information between them, even after the pages have been
closed.

JavaScript is a scripting language designed primarily for adding interactivity to Web pages and
creating Web applications. JavaScript is the scripting language implemented on web, which is used to
add several functionalities, validating the form, as well as communicating with servers etc.
JavaScript (is) is a light-weight object-oriented programming language which is used by several
websites for scripting the webpages. It is an interpreted, full-fledged programming language that
enables dynamic interactivity on websites when applied to an HTML document.

4.1.1 Features of JavaScript


There are following features of JavaScript:
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it
is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather
than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
8. It provides good control to the users over the web browsers.

4.1.2 Application of JavaScript


JavaScript is used to create interactive websites. It is mainly used for:

108
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialogbox and prompt dialog box),
o Displaying clocks etc.

Example
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document. Write ("Hello JavaScript by JavaScript");
</script>
</body>
</html>

4.1.3 3 Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .cs.js file (external javaScript)

Between the body tag


<html>
<body>
<script
type="text/JavaScript"> alert
("Hello Java point").
</script>
</body>
</html>

Between the head tag


<html>
<head>
<script type="text/JavaScript">
function msg (){
alert ("Hello Java point").

109
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg ()"/>
</form>
</body>
</html>

External
JavaScript
Message.js
function msg (){
alert ("Hello Java point").
}

<html>
<head>
<script type="text/JavaScript" src="message.js"></script>

</head>
<body>
<p>Welcome to JavaScript</p>

<form>
<input type="button" value="click" onclick="msg ()"/>

</form>
</body>

</html>
4.1.4 JavaScript Data Types

JavaScript provides different data types to hold different types of values. There are two types of
data types in JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
110
JavaScript is a dynamic type of language; means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc. For example:
var a=40;//holding number var
b="Rahul";//holding string

4.1.4.1 Primitive data types


Table 4.1 Primitive Datatypes

Data Type Description

String represents sequence of characters e.g., "hello"

Number represents numeric values e.g., 100

Boolean represents Boolean value either false or true

Undefined represents undefined value

Null represents null i.e., no value at all

Table 4.2 Non-primitive data types

Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression

4.1.6 JavaScript Operators


JavaScript operators are symbols that are used to perform operations on operands. There
are following types of operators in JavaScript
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
111
5. Assignment Operators
6. Special Operators
4.1.7 JavaScript Special Operators
The following operators are known as JavaScript special operators.
Table 4.3 JavaScript operators

Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

4.1.8 JavaScript Functions


JavaScript functions are used to perform operations. We can call JavaScript function manytimes
to reuse the code.
Syntax
function functionName ([arg1, arg2, ...argN]){
//code to be executed
}

example of function in JavaScript


<script>
function msg(){
alert("hello! this is message");

112
}

</script>
<input type="button" onclick="msg()" value="call function"/>

function by passing arguments


<html>
<body>
<script>
function getcube(number){
alert(number*number*number).
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

function that returns a value


<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script> document.
Write(getInfo());
</script>
</body>
</html>

JavaScript Function Object


In JavaScript, the purpose of Function constructor is to create a new Function object. It
executes the code globally. However, if we call the constructor directly, a function is created
dynamically but in an unsecured way.

Syntax
new Function ([arg1[, arg2[, argn]],] functionBody)

113
arg1, arg2, .... , argn - It represents the argument used by function.
functionBody - It represents the function definition

Table 4.4 Function Methods

Method Description

apply () It is used to call a function contains this value and a single array of
arguments.

bind () It is used to create a new function.

call () It is used to call a function contains this value and an argument list.

to String () It returns the result in a form of a string.

example to display the sum of given numbers


<!DOCTYPE html>
<html>
<body>
<script>
var add=new Function ("num1","num2","return num1+num2");
document. writeln(add(2,5));
</script>
</body>
</html>

4.1.9 Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)

syntax of creating array using array literal


var arrayname=[value1,value2 ..... valueN];
example of creating and using array in JavaScript
<html>
<body>

114
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

syntax of creating array directly


var arrayname=new Array();
new keyword is used to create instance of array
<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>

JavaScript array constructor


example of creating object by array constructor
<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
115
</script>
</body>
</html>
Array Methods

Table 4.5 Array Methods

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value
pair.

every() It determines whether all the elements of an array are satisfying the
provided function conditions.

flat() It creates a new array carrying sub-array elements concatenated recursively


till the specified depth.

flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.

fill() It fills elements into an array with static values.

from() It creates a new array carrying the exact copy of another arrayelement.

filter() It returns the new array containing the elements that pass the provided
function conditions.

find() It returns the value of the first element in the given array that satisfies the
specified condition.

findIndex() It returns the index value of the first element in the given array that
satisfies the specified condition.

116
forEach() It invokes the provided function once for each element of an array.

includes() It checks whether the given array contains the specified element.

indexOf() It searches the specified element in the given array and returns the index of
the first match.

isArray() It tests if the passed value ia an array.

join() It joins the elements of an array as a string.

keys() It creates an iterator object that contains only the keys of the array, then
loops through these keys.

lastIndexOf() It searches the specified element in the given array and returns the index of
the last match.

map() It calls the specified function for every array element and returns the
new array

of() It creates a new array from a variable number of arguments, holding any
type of argument.

pop() It removes and returns the last element of an array.

push() It adds one or more elements to the end of an array.

reverse() It reverses the elements of given array.

reduce(function, It executes a provided function for each value from left to right and
initial) reduces the array to a single value.

reduceRight() It executes a provided function for each value from right to left and
reduces the array to a single value.

some() It determines if any element of the array passes the test of the
implemented function.

117
shift() It removes and returns the first element of an array.

slice() It returns a new array containing the copy of the part of the given array.

sort() It returns the element of the given array in a sorted order.

splice() It add/remove elements to/from the given array.

toLocaleString() It returns a string containing all the elements of a specified array.

toString() It converts the elements of a specified array into string form, without
affecting the original array.

unshift() It adds one or more elements in the beginning of the given array.

values() It creates a new iterator object carrying values for each index in the
array.

4.2 JavaScript – Objects

JavaScript Objects

JavaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc. JavaScript is template based not class based. Here,
we don't create class to get the object. But, we direct create objects
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keywor

syntax of creating object using object literal


object={property1:value1, property2:value2 ... propertyN:valueN}
property and value is separated by : (colon).
example of creating object
<html>
<body>

118
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

By creating instance of Object syntax of creating object directly


var objectname=new Object();

example of creating object directly


<html>
<body>
<script>
var emp=new Object();
emp.id=101; emp.name="Ravi
Malik"; emp.salary=50000;
document. Write (emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>

By using an Object constructor


<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name; this.salary=salary;
}
e=new emp (103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>

Here, you need to create function with arguments. Each argument value can be assigned in the

119
current object by using this keyword.
This keyword refers to the current object

4.2.1 Defining method in JavaScript Object


We can define method in JavaScript object. But before defining method, we need to add property
in the function with same name as method.
example of defining method in object

<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
</body>
</html>

JavaScript has several built-in or native objects. These objects are accessible anywhere in your
program and will work the same way in any browser running in any operating system.

Here is the list of all important JavaScript Native Objects −

 JavaScript Number Object


 JavaScript Boolean Object
 JavaScript String Object
 JavaScript Array Object
 JavaScript Date Object
 JavaScript Math Object

120
 JavaScript RegExp Object

4.2.2 The Number Object

The Number object represents numerical date, either integers or floating-point numbers. In general,
you do not need to worry about Number objects because the browser automaticallyconverts
number literals to instances of the number class.

Syntax

The syntax for creating a number object is as follows −

var val = new Number(number);

In the place of number, if you provide any non-number argument, then the argument cannotbe
converted into a number, it returns NaN (Not-a-Number).

Number Properties

Here is a list of each property and their description.

Table 4.6 Number properties

Property Description

The largest possible value a number in JavaScript can have


MAX_VALUE 1.7976931348623157E+308

The smallest possible value a number in JavaScript can have 5E-324


MIN_VALUE
Equal to a value that is not a number.
NaN

NEGATIVE_INFINIT A value that is less than MIN_VALUE.


Y
A value that is greater than MAX_VALUE
POSITIVE_INFINITY
A static property of the Number object. Use the prototype property to
assign new properties and methods to the Number object in the current
prototype
document

Returns the function that created this object's instance. By default this is
constructor the Number object.

In the following sections, we will take a few examples to demonstrate the properties ofNumber.

121
Number Methods

The Number object contains only the default methods that are a part of every object'sdefinition.

Table 4.7 Number Methods

Method Description

Forces a number to display in exponential notation, even if the number is in the range
toExponential() in which JavaScript normally uses standard notation.

Formats a number with a specific number of digits to the right of the decimal.
toFixed()
Returns a string value version of the current number in a format that may vary
toLocaleString() according to a browser's local settings.

Defines how many total digits (including digits to the left and right of the
toPrecision() decimal) to display of a number.

Returns the string representation of the number's value.


toString()
Returns the number's value.
valueOf()

4.2.3 The Boolean Object

The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is
0, -0, null, false, NaN, undefined, or the empty string (""), the object has aninitial value of false.

Syntax

Use the following syntax to create a boolean object.

Boolean Properties

Here is a list of the properties of Boolean object –

Table 4.8 Boolean properties

Property Description

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


constructor
The prototype property allows you to add properties and methods to an object.
prototype

In the following sections, we will have a few examples to illustrate the properties of Boolean object.

122
4.3.4 Boolean Methods

Here is a list of the methods of Boolean object and their description.

Table 4.9 Bollean Methods

Method Description

Returns a string containing the source of the Boolean object; you can use this
toSource() string to create an equivalent object.

Returns a string of either "true" or "false" depending upon the value of the
toString() object.

Returns the primitive value of the Boolean object.


valueOf()

4.2.5 The Strings Object

The String object lets you work with a series of characters; it wraps Javascript's stringprimitive
data type with a number of helper methods.

As JavaScript automatically converts between string primitives and String objects, you cancall any
of the helper methods of the String object on a string primitive.

Syntax

Use the following syntax to create a String object −

var val = new String(string);


The String parameter is a series of characters that has been properly encoded.

String Properties

Here is a list of the properties of String object and their description.

Table 4.10 String properties


Property Description

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


constructor
Returns the length of the string.
length
The prototype property allows you to add properties and methods to an object.
prototype

123
In the following sections, we will have a few examples to demonstrate the usage of Stringproperties.

String Methods

Here is a list of the methods available in String object along with their description.

Table 4.11String Methods

Method Description

Returns the character at the specified index.


charAt()
Returns a number indicating the Unicode value of the character at the given
charCodeAt() index.

Combines the text of two strings and returns a new string.


concat()
Returns the index within the calling String object of the first occurrence of
indexOf() the specified value, or -1 if not found.

Returns the index within the calling String object of the last occurrence of
lastIndexOf() the specified value, or -1 if not found.

Returns a number indicating whether a reference string comes before or


localeCompare() after or is the same as the given string in sort order.

Used to match a regular expression against a string.


match()
Used to find a match between a regular expression and a string, and to
replace() replace the matched substring with a new substring.

search() Executes the search for a match between a regular expression and a

specified string.

Extracts a section of a string and returns a new string.


slice()
Splits a String object into an array of strings by separating the string into
split() substrings.

Returns the characters in a string beginning at the specified location


substr() through the specified number of characters.

Returns the characters in a string between two indexes into the string.
substring()

124
The characters within a string are converted to lower case while respecting
toLocaleLowerCa the current locale.
se()
The characters within a string are converted to upper case while respecting
toLocaleUpperCa the current locale.
se()
Returns the calling string value converted to lower case.
toLowerCase()
Returns a string representing the specified object.
toString()
Returns the calling string value converted to uppercase.
toUpperCase()
Returns the primitive value of the specified object.
valueOf()

String HTML Wrappers

Here is a list of the methods that return a copy of the string wrapped inside an appropriateHTML tag.
Table 4.12 String Wrappers

Method Description

Creates an HTML anchor that is used as a hypertext target.


anchor()
Creates a string to be displayed in a big font as if it were in a <big> tag.
big()
Creates a string to blink as if it were in a <blink> tag.
blink()
Creates a string to be displayed as bold as if it were in a <b> tag.
bold()
Causes a string to be displayed in fixed-pitch font as if it were in a <tt> tag
fixed()
fontcolor() Causes a string to be displayed in the specified color as if it were in a <font

color="color"> tag.

Causes a string to be displayed in the specified font size as if it were in a <font


fontsize() size="size"> tag.

Causes a string to be italic, as if it were in an <i> tag.


italics()
Creates an HTML hypertext link that requests another URL.
link()
Causes a string to be displayed in a small font, as if it were in a <small> tag.
small()
Causes a string to be displayed as struck-out text, as if it were in a <strike> tag.
strike()
Causes a string to be displayed as a subscript, as if it were in a <sub> tag
sub()

125
Causes a string to be displayed as a superscript, as if it were in a <sup> tag
sup()

4.2.6 The Arrays Object

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

Syntax

Use the following syntax to create an Array object −

var fruits = 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 fruits = [ "apple", "orange", "mango" ];

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

fruits[0] is the first element fruits[1] is the


second elementfruits[2] is the third element
Array Properties

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

Table 4.13 Array properties

Property Description

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


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

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

Reflects the number of elements in an array.


length
The prototype property allows you to add properties and methods to an object.
prototype

126
In the following sections, we will have a few examples to illustrate the usage of Arrayproperties.

Array Methods

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

Table 4.14 Array Methods

Method Description

Returns a new array comprised of this array joined with other array(s) and/or
concat() value(s).

Returns true if every element in this array satisfies the provided testing
every() function.

Creates a new array with all of the elements of this array for which the provided
filter() filtering function returns true.

Calls a function for each element in the array.


forEach()
Returns the first (least) index of an element within the array equal to the
indexOf() specified value, or -1 if none is found.

Joins all elements of an array into a string.


join()
Returns the last (greatest) index of an element within the array equal to the
lastIndexOf() specified value, or -1 if none is found.

map() Creates a new array with the results of calling a provided function on every

element in this array.

Removes the last element from an array and returns that element.
pop()
Adds one or more elements to the end of an array and returns the new length
push() of the array.

Apply a function simultaneously against two values of the array (from left-
reduce() to-right) as to reduce it to a single value.

Apply a function simultaneously against two values of the array (from right-
reduceRight() to-left) as to reduce it to a single value.

Reverses the order of the elements of an array -- the first becomes the last, and
reverse() the last becomes the first.

127
Removes the first element from an array and returns that element.
shift()
Extracts a section of an array and returns a new array.
slice()
Returns true if at least one element in this array satisfies the provided testing
some() function.

Represents the source code of an object


toSource()
Represents the source code of an object
sort()
Adds and/or removes elements from an array.
splice()
Returns a string representing the array and its elements.
toString()
Adds one or more elements to the front of an array and returns the new length
unshift() of the array.

4.2.7 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 few methods allow you to operate on it. Most methodssimply 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.
Syntax

You can use any of the following syntaxes to create a Date object using Date () constructor.

new Date( )
new Date(milliseconds)new
Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Date Methods
Here is a list of the methods used with Date and their description.

Table 4.15 Date Methods

Method Descrip
tion
Returns today's date and time
Date()
Returns the day of the month for the specified date according to
getDate() local time.

128
Returns the day of the week for the specified date according to
getDay() local time.

Returns the year of the specified date according to local time.


getFullYear()
Returns the hour in the specified date according to local time.
getHours()
Returns the milliseconds in the specified date according to local
getMilliseconds()
time.
Returns the minutes in the specified date according to local time.
getMinutes()
Returns the month in the specified date according to local time.
getMonth()
Returns the seconds in the specified date according to local time.
getSeconds()
Returns the numeric value of the specified date as the number
getTime() of milliseconds since January 1, 1970, 00:00:00 UTC.

Returns the time-zone offset in minutes for the current locale.


getTimezoneOffset()
Returns the day (date) of the month in the specified date according
getUTCDate() to universal time.

Returns the day of the week in the specified date according


getUTCDay() to universal time.

Returns the year in the specified date according to universal time.


getUTCFullYear()
Returns the hours in the specified date according to universal time.
getUTCHours()
Returns the milliseconds in the specified date according to universal
getUTCMilliseconds time.
()
Returns the minutes in the specified date according to universal time.
getUTCMinutes()
Returns the month in the specified date according to universal time.
getUTCMonth()
Returns the seconds in the specified date according to universal time.
getUTCSeconds()
Deprecated - Returns the year in the specified date according to local
getYear() time. Use getFullYear instead.

Sets the day of the month for a specified date according to local time.
setDate()
Sets the full year for a specified date according to local time.
setFullYear()
Sets the hours for a specified date according to local time.
setHours()

129
Sets the milliseconds for a specified date according to local time.
setMilliseconds()
Sets the minutes for a specified date according to local time.
setMinutes()
Sets the month for a specified date according to local time.
setMonth()
Sets the seconds for a specified date according to local time.
setSeconds()
Sets the Date object to the time represented by a number of
setTime() milliseconds since January 1, 1970, 00:00:00 UTC.

Sets the day of the month for a specified date according to universal
setUTCDate() time.

Sets the full year for a specified date according to universal time.
setUTCFullYear()
Sets the hour for a specified date according to universal time.
setUTCHours()

setUTCMilliseconds Sets the milliseconds for a specified date according to universal time.
()
Sets the minutes for a specified date according to universal time.
setUTCMinutes()
Sets the month for a specified date according to universal time.
setUTCMonth()

Sets the seconds for a specified date according to universal time.


setUTCSeconds()
Deprecated - Sets the year for a specified date according to
setYear() local time. Use setFullYear instead.

Returns the "date" portion of the Date as a human-readable string.


toDateString()
Deprecated - Converts a date to a string, using the Internet
toGMTString() GMT conventions. Use toUTCString instead.

Returns the "date" portion of the Date as a string, using the current
toLocaleDateString() locale's conventions.

Converts a date to a string, using a format string.


toLocaleFormat()
Converts a date to a string, using the current locale's conventions.
toLocaleString()
Returns the "time" portion of the Date as a string, using the current
toLocaleTimeString() locale's conventions.

Returns a string representing the source for an equivalent Date


toSource() object; you can use this value to create a new object.

130
Returns a string representing the specified Date object.
toString()
Returns the "time" portion of the Date as a human-readable string.
toTimeString()
Converts a date to a string, using the universal time convention.
toUTCString()
Returns the primitive value of a Date object.
valueOf()

Example:

function start()
{
var current = new Date();

// string formatting methods and valueOf document.getElementById(


"strings" ).innerHTML =
"<p>toString: " + current.toString() + "</p>" + "<p>toLocaleString: " +
current.toLocaleString() + "</p>" + "<p>toUTCString: " +
current.toUTCString() + "</p>" + "<p>valueOf: " + current.valueOf() +
"</p>";

// get methods
document.getElementById( "getMethods" ).innerHTML =
"<p>getDate: " + current.getDate() + "</p>" + "<p>getDay: " +
current.getDay() + "</p>" + "<p>getMonth: " + current.getMonth() +
"</p>" + "<p>getFullYear: " + current.getFullYear() + "</p>" +
"<p>getTime: " + current.getTime() + "</p>" + "<p>getHours: " +
current.getHours() + "</p>" + "<p>getMinutes: " +
current.getMinutes() + "</p>" + "<p>getSeconds: " +
current.getSeconds() + "</p>" +
"<p>getMilliseconds: " + current.getMilliseconds() + "</p>" + "<p>getTimezoneOffset: " +
current.getTimezoneOffset() + "</p>";

// creating a Date
var anotherDate = new Date( 2011, 2, 18, 1, 5, 0, 0 ); document.getElementById(
"newArguments" ).innerHTML =
"<p>Date: " + anotherDate + "</p>";

// set methods anotherDate.setDate( 31 );


anotherDate.setMonth( 11 );
anotherDate.setFullYear( 2011 );
anotherDate.setHours( 23 );
anotherDate.setMinutes( 59 );
anotherDate.setSeconds( 59 ); document.getElementById( "setMethods"
).innerHTML =
"<p>Modified date: " + anotherDate + "</p>";
} // end function start window.addEventListener( "load", start,

false );

131
4.2.8 The Math Object
The math object provides you properties and methods for mathematical constants and functions. Unlike other
global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by
using Math as an object without creating it.

Syntax

The syntax to call the properties and methods of Math are as follows

var pi_val = Math.PI;


var sine_val = Math.sin(30);

Math Properties

Here is a list of all the properties of Math and their description.

Table 4.16 Math properties

Property Description

E\ Euler's constant and the base of natural logarithms, approximately 2.718.

LN2 Natural logarithm of 2, approximately 0.693.

LN10 Natural logarithm of 10, approximately 2.302.

LOG2E Base 2 logarithm of E, approximately 1.442.

LOG10E Base 10 logarithm of E, approximately 0.434.

PI Ratio of the circumference of a circle to its diameter, approximately 3.14159.

Square root of 1/2; equivalently, 1 over the square root of 2, approximately


SQRT1_2
0.707.

SQRT2 Square root of 2, approximately 1.414.

In the following sections, we will have a few examples to demonstrate the usage of Math properties.
Math Methods

Here is a list of the methods associated with Math object and their description

132
Table 4.17 Math Methods

Method Description

abs() Returns the absolute value of a number.

acos() Returns the arccosine (in radians) of a number.

asin() Returns the arcsine (in radians) of a number.

atan() Returns the arctangent (in radians) of a number.

atan2() Returns the arctangent of the quotient of its arguments.

ceil() Returns the smallest integer greater than or equal to a number.

cos() Returns the cosine of a number.

Returns EN, where N is the argument, and E is Euler's constant, the base of the
exp()
natural logarithm.

floor() Returns the largest integer less than or equal to a number.

log() Returns the natural logarithm (base E) of a number.

max() Returns the largest of zero or more numbers.

min() Returns the smallest of zero or more numbers.

pow() Returns base to the exponent power, that is, base exponent.

random() Returns a pseudo-random number between 0 and 1.

round() Returns the value of a number rounded to the nearest integer.

sin() Returns the sine of a number.

sqrt() Returns the square root of a number.

tan() Returns the tangent of a number.

toSource() Returns the string "Math".

3.13 JSON

JSON is used to store information in an organized, and easy-to-access manner. Its full form is

133
JavaScript Object Notation. It offers a human-readable collection of data which can be accessed
logically.
Its filename extension for written programming code is .json. The Internet Media type for JSON is
application/json and the public. json is its Uniform Type Identifier. The file name extension is. json.

Why use JSON?


Here are the important benefits/ pros of using JSON:
 Provide support for all browsers
 Easy to read and write
 Straightforward syntax
 You can natively parse in JavaScript using eval () function
 Easy to create and manipulate
 Supported by all major JavaScript frameworks
 Supported by most backend technologies
 JSON is recognized natively by JavaScript
 It allows you to transmit and serialize structured data using a network connection.
 You can use it with modern programming languages.
 JSON is text which can be converted to any object of JavaScript into JSON and send this JSON
to the server.
4.3.1 Features of JSON
Easy to use - JSON API offers high-level facade, which helps you to simplify commonly
used use-cases.
Performance - JSON is quite fast as it consumes very less memory space, which is especially
suitable for large object graphs or systems.
Free tool - JSON library is open source and free to use.
Doesn't require to create mapping - Jackson API provides default mapping for manyobjects to
be serialized.
Clean JSON - Creates clean, and compatible JSON result that is easy to read.
Dependency - JSON library does not require any other library for processing.

Rules for JSON Syntax


 Data should be in name/value pairs
 Data should be separated by commas
 Curly braces should hold objects
 Square brackets hold arrays

134
4.3.2 Data Types in JSON
Table 4.18 Data types in JSON

Data Type Description

Number It includes real number, integer, or a floating number

String It consists of any text or Unicode double-quoted with


backslash escapement

Boolean The Boolean data type represents either True or False values

Null The Null value denotes that the associated variable doesn't
have any value

Object It is a collection of key-value pairs and always separated by a


comma and enclosed in curly brackets.
Array It is an ordered sequence of values separated.

Number:
 The number is a double-precision floating-point format which depends on its
implementation method.
 In JSON you can't use Hexadecimal and Octal formats.

Table 4.19 Number properties


Type Description

Integer Number 1-9, and 0. Both positive and negative numbers.


Fraction Fractions like 3

Exponent Exponent like e, e+

Syntax:
var json-object-name = {string : number_value,. .............. }

Example:
var obj = {salary: 2600}

135
String:
It is a series of double-quoted Unicode characters and having backslash escaping.

Table 4.20 operators

Type Description

* Use for double quotation typing

/ Use for solidus


\ Use for reverse solidus

B Use to add backspace

F From feed

N To create a new line

R Use for carriage return

T To show horizontal tab


U Hexadecimal digits

Syntax
var json-object-name = {string : "string value",…..}
Example:

var obj= {name: 'Andy'}

Boolean
It stores only true or false values.

Syntax:
var json-object-name = {string: true/false, …..}

Example:
4.3.3 Array
var obj = {active: 'true'}

136
It is an ordered collection of values.
You should use an array when the key names are sequential integers.
It should be enclosed inside square brackets which should be separated by ',' (comma)
Syntax:
[value,.............. ]

Example:
{
"eBooks‖: [
{
"language":"Pascal",
"edition":"third"
},
{
"language":"Python",
"edition":"four"
},
{
"language":"SQL",
"edition":"second"
}
]
}

4.3.4 OBJECT
An objet shoul enclosed in curly braces,
It should be an unordered set of name or value pairs.
Name should be followed by ":" (colon)and the name/value pairs need to be separated using "," (comma).
You can use it when key names are arbitrary strings.
Syntax:
{ string : value, ….. }

Example:
{
"id": 110,
"language": "Python", "price":
1900,
}

137
Whitespace
You can insert whitespace between a pair of tokens.
Syntax:
{string:" ",….}

Example:
var a = " Alex"; var b = "Steve";

Example of JSON
The given code example defines how to use JSON to store information related to
programming books along with edition and author name.
{
"book":[
{
"id":"444",
"language":"C",
"edition":"First", "author":"Dennis
Ritchie "
},
{
"id":"555",
"language":"C++",
"edition":"second", "author":" Bjarne
Stroustrup "
}
]
}
Lets understand JSON format with another example. Here, JSON defines the first name, last name and
id of a student.
{
"student": [
{
"id":"01",
"name": "Tom", "lastname":
"Price"
},
{
"id":"02",
"name": "Nick", "lastname":

138
"Thameson"
}
]
}
4.3.5 Application of JSON
 Helps you to transfer data from a server
 JSON format helps transmit and serialize all types of structured data.
 Allows you to perform asynchronous data calls without the need to do a page refresh
 Helps you to transmit data between a server and web applications.
 It is widely used for JavaScript-based application, which includes browser extension and
websites.
 You can transmit data between the server and web application using JSON.
 We can use JSON with modern programming languages.
 It is used for writing JavaScript-based applications that include browser add-ons.
 Web services and Restful APIs use the JSON format to get public data.

4.4 Understanding the DOM
Every web page resides a browser window which can be considered as an object. A document
object represents the HTML documents that is displayed in that window. The document object has
various properties that refer to other objects which allow access to and modification of document
content. The way that document content is accessed and modified is called the Document Object
Model. The Objects are organized in a hierarchy. This hierarchical structure applies to the
organization of objects in a web document. Window Object: Top of the hierarchy. It is the outmost
element of the object hierarchy.

Document Object: Each HTML document that gets loaded into a window becomes a document object.
The document contains the content of the page.
Form Object: Everything enclosed in the <form>… </form> tags set the form object.
Form Control Elements: The form object contains all the elements defined for that object such as text
fields, buttons, radio buttons, and checkboxes.
Here is a simple hierarchy of few important objects
Window
Frame Parent Self top

Levels of Document Object Model


The Document Object Model has been under development by W3C, and it is developed in various
levels. These levels are

Table 4.21 DOM Levels

Level Description
DOM THIS MODEL IS SUPPORTED BY THE EARLY BROWSERS. THIS LEVEL
0 COULD SUPPORT JavaScript. This version was implemented in Netscape 3.0 and
Internet Explorer 3.0 browsers.

139
DOM This version was issued in 1998 which was focused on XHTML and XML
1
DOM This version was issued in 2000 that could specify the style sheet. It also supports the
2 event model and traversal within the documents.
DOM 3 This is the current release of DOM specification published in 2004. This version could deal
with XML with DTD and schema, document validations, document views and formatting.

Basically DOM is an Application Programming Interface (API) that defines the interface between XHTML
document and application program. That means, suppose application program is written in java and this java
program wants to access the elements of XHTML web document then it is possible by using a set of
Application Programming Interfaces(API) which belongs to the DOM.
4.5 JavaScript Events and Input Validation.
Event Handling
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When JavaScript code is
included in HTML, is react over these events and allow the execution. This process of reacting
over the events is called Event Handling.
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.
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.

4.5.1 Mouse events:

Table 4.22 Mouse Events

Event Event Handler Description


Performe
d
click onclick When mouse click on an element

mouseover on mouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an


element

140
mousedown onmousedown When the mouse button is pressed over the
element

mouseup onmouseup When the mouse button is released over the


element

mousemove onmousemove When the mouse movement takes place.

4.5.2 Keyboard events:

Table 4.23 Keyboard Events

Event Performed Event Handler Description

Keydown & Keyup onkeydown When the user press and then release the key

&onkeyup
4.5.3 Form events:
Table 4.24 Form Events

Event Performed Event Description


Handle
r
focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a


form element

141
4.5.4 Window/Document events

Table 4.25 Window document Events

Event Event Handler Description

Performed

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the browser

4.5.5 Click Event


<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
4.5.6 MouseOver Event
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>

142
<script language="Javascript" type="text/Javascript"> function
mouseoverevent()
{
alert("This is JavaTpoint");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

4.5.7 Focus Event


<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
function focusevent()
{
document.getElementById("input1").style.background=" aqua";
}
</script>
</body>
</html>

4.5.8 Keydown Event


<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
function keydownevent()
{
}
</script>
</body>
</html
>

143
document.getElementById("input1");
alert("Pressed a key");

4.5.8 Load event


<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
4.5.9 Input Validation
<html>
<head>
<script type="text/javascript">
var fl=1;
function check()
{
var n=document.forms[0].elements[0].value;
var re=new RegExp("^[0-9]");

xyz.innerText="";
if(n.length<1)
{
xyz.innerText="invalid user name";
fl=0;
}
if(re.test(n))
{
xyz.innerText="User name should not start with a digit";
fl=0;
}
}
function check1()
{
xyz1.innerText="";
var name1=document.getElementById("pwd").value;
if(name1.length<1)
{
xyz1.innerText="Field should be filled";
fl=0;

144
}
}
function check2()
{
xyz2.innerText="";
var name2=document.getElementById("pwd1").value;
var name1=document.getElementById("pwd").value;
if(name2.length<1)
{
xyz2.innerText="Field should be filled";
fl=0;
}
if(name1!=name2)
{
xyz2.innerText="passwords mismatched";
fl=0;
}
}
function email()
{
p1.innerText="";
var m1=document.getElementById("mail").value;
var re1=new RegExp("^[0-9]");

if(m1=="")
{
p1.innerText="please enter email id";
fl=0;

}
if(re1.test(m1))
{
p1.innerText="mail id should not start with a digit";
fl=0;
}

}
function addr()
{
p2.innerText="";
var adr=document.getElementById("ad").value;
if(adr=="")
{
p2.innerText="field should be filled";
fl=0;
}
}
function showit()
{

145
if(fl==0)
alert("Your registration was not successful");
else
alert("your registration was successful");
}
</script>
</head>
<body bgcolor="beige" text="black">
<form method="get">
<table align="center">
<tr>
<td>
<h1 align="center"> Email Regestration</h1>
<h3 align="center"> User
Name&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" id="uname" onBlur="check()"></h3>
</td>

<td>
<p id="xyz"></p>
</td>
</tr>

<tr>
<td>
<h3 align="center">
Password&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;:
<input type="password" id="pwd" onBlur="check1()"></h3>
</td>
<td>
<p id="xyz1"></p>
</td>
</tr>

<tr>
<td>
<h3 align="center">Confirm password:
<input type="password" id="pwd1" onBlur="check2()"></h3>
</td>
<td>
<p id="xyz2">
</td>

</tr>
<tr>
<td>
<h3 align="center">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbs
p;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n

146
bsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Email
Address&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="mail" onBlur="email()">&nbsp;@
<select size="1" name="mail1" tabindex="9">
<option value="1">gmail</option>
<option value="1">yahoo</option>
<option value="1">rediffmail</option>
<option value="1">hotmail</option>
<option value="1">msn</option></select>&nbsp;&nbsp;.
<select size="1" name="mail2" tabindex="9">
<option value="1">com</option>
<option value="1">co.in</option>
</h3>

</td>
<td>
<p id="p1"></p>
</td>
</tr>

<tr>
<td>
<br>
<h3 align="center">
Address&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="ad" onBlur="addr()"></h3>
</td>
<td>
<p id="p2"></p>
</td>
</tr>

<tr>
<td>
<h3 align="center">
Line1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="l1"></h3>
</td>
</tr>

<tr>
<td>
<h3 align="center">
Line2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&n
bsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="l2"></h3>
</td>
</tr>

147
<tr>
<td>
<h3 align="center">
Pin&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;:
<input type="text" name="pin"></h3>
</td>
</tr>
</table>
<br>
<h3 align="center"><input type="submit" value="submit" onClick="showit()">
<input type="reset" value="reset">
</h3>
</form>
</body>
</html>
OUTPUT:
Login: Karups

Fig: - 4.1 output of E-mail Registration

4.6 Modifying CSS Elements using JavaScript.


JavaScript is a programming language. JavaScript is widely used to provide interactivity in web sites and
applications. JavaScript can interact with stylesheets, allowing you to write programs that change a
document‘s style dynamically.

There are three ways to do this:

By working with the document‘s list of stylesheets—for example: adding, removing or modifying a stylesheet.

By working with the rules in a stylesheet—for example: adding, removing or modifying a rule.

By working with an individual element in the DOM—modifying its style independently of the document‘s

148
stylesheets

Action: A JavaScript demonstration

Make a new HTML document, doc5.html. Copy and paste the content from here, making sure that you
scroll to get all of it:

<!DOCTYPE html>

<html>

<head>

<title>Mozilla CSS Getting Started - JavaScript


demonstration</title>

<link rel="stylesheet" type="text/css" href="style5.css" />

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

</head>

<body>

<h1>JavaScript sample</h1>

<div id="square"></div>

<button type="button" id="clickMe">Click Me</button>

</body>

</html>

Make a new CSS file, style5.css. Copy and paste the content
from here:

#square {

width: 20em;

height: 20em;

border: 2px inset gray;

margin-bottom: 1em;

button {

padding: .5em 2em;

149
}

Make a new text file, script5.js. Copy and paste the content
from here:

// JavaScript demonstration

var square = document.getElementById("square"),

clickMe = document.getElementById('clickMe'); //Keeping


it unobstrusive

function doDemo () {

var button = this;

square.style.backgroundColor = "#fa4";

button.setAttribute("disabled", "true");

setTimeout(clearDemo, 2000, button);

function clearDemo (button) {

var square = document.getElementById("square");

square.style.backgroundColor = "transparent";

button.removeAttribute("disabled");

clickMe.onclick = doDemo; //Onclick call. Pass no arguments.

Open the document in your browser and press the button.

What this code does, is that it changes the background color of the #square to #ffaa44. Here‘s a JSFiddle
so you can see it working live.

The HTML document links the stylesheet as usual, and it also links the script.

The script works with individual elements in the DOM. It modifies the square‘s style directly. It
modifies the button‘s style indirectly by changing an attribute.

In JavaScript, document.getElementById("square") is similar in function to to the CSS selector #square


and in a similar way, document.getElementById('clickMe') is similar to #clickMe.

150
In JavaScript, backgroundColor corresponds to the CSS property background-color. JavaScript does not
allow hyphens in names, so ―camelCase‖ is used instead.

Your browser has a built-in CSS rule for button that changes the button‘s appearance when it is disabled.

4.7 JavaScript Local Storage


HTML5 includes two new ways to store data on the client – local storage and session storage. Local
storage has no time limit on how long the data should be kept around, session storage on the other hand
(as the name suggests) stores data for only one session.

Traditionally you can store data on the client using cookies, but they are not suited for storing large
amounts of data because everything gets sent back to the server on every request and hence slows down
the roundtrip and making the user experience less enjoyable.

Using the new storage methods, data is only passed on when asked for and it‘s therefore possible to store
large amounts of data without slowing down the site. The data is also sandboxed and a website can only
access data stored by itself, you can use JavaScript to set and get data from the relevant storage.

Browser Support Detection

A browser that supports HTML5‘s local storage will have a local Storage property on the
global window object, you can write your own function to check for the existence of and validity (not null) of
the local Storage property, or use a third-party library like Modernizr.

Modernizr is an open source, light weight javascript library that detects support for many HTML5 and CSS3
features, when it runs it creates a global object called Modernizr. To check for local storage support, all you
need to do is to check the boolean flag for local storage:

1 if (Modernizr.localstorage) {

2 // browser supports local storage

3 }

4 else {

5 // browser doesn't support local storage

6 }

or similarly for session storage:

1 if (Modernizr.sessionstorage) {

2 // browser supports local storage

151
3 }

4 else {

5 // browser doesn't support local storage

6 }

4.8 Ajax.

Introduction to AJAX
 AJAX stands for Asynchronous Javascript And XML.
 AJAX is not a programming language.
 AJAX is a way of using existing standards (JavaScript and XML) to make more interactive web
applications.
 AJAX was popularized in 2005 by Google (with Google suggest)

4.8.1 An AJAX Application


• Recall the standard HTTP transaction
1. Client opens connection to server
2. Client sends request to server
3. Server sends reply to client
4. Client and server close connection

• After Step 4, the client renders the document and this may include running some JavaScript.

• In an AJAX application, the JavaScript code then communicates with the server behind the scenes.

 Communication with the server takes place asynchronously, and transparently to the user
 Data is exchanged with the server without the need for a page reload • This is accomplished through a
special kind of HTTP request.

An AJAX – Examples
 Google Maps
 Google Suggest
 Gmail
 Yahoo Maps (new)

4.8.2 AJAX - Browser Support


All the available browsers cannot support AJAX. Here is a list of major browsers, that support AJAX.
 Mozilla Firefox 1.0 and above.
 Netscape version 7.1 and above.
 Apple Safari 1.2 and above.
 Microsoft Internet Explorer 5 and above.
 Konqueror.
 Opera 7.6 and above.

152
Typical AJAX Event
• A typical AJAX transaction looks like this:

1. User triggers some event (presses a key, moves mouse, ...)

2.Event handler code sends HTTP request to server

3. Server replies triggering code on client


4. Reply handler code updates web page using server's reply

• Between steps 2 and 3 the web page is still usable (event is asynchronous)

• At no point during the transaction does the browser open a new web page

4.8.3 Pros and Cons of AJAX


• Pros:
– Allows web applications to interact with data on the server

– Avoid clunky GET/POST send/receive interfaces

– web apps look more and more like real applications

– Some applications can only be realized this way

• E.g.: Google Suggest offers interactive access to one of the largest data collections in
the world – For office style applications, user's data is stored on a reliable server, accessible
from anyweb browser

• Cons:

– Tough to make compatible across all browsers

– Should have a low-latency connection to the server

– Can be server intensive

• E.g.: Google Suggest generates a search for every keystroke entered.

153
4.8.4 An AJAX Architecture

Fig-4.2 Ajax Architecture


XMLHttpRequest object plays a important role.

1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.

4.8.5 Setting up an AJAX Transaction


• Create an XMLHTTPRequest object

• Set up the request's onreadystatechange function

• Open the request

• Send the request

4.8.6 Creating an XMLHTTPRequest Object


function sendRequest()

var xmlHttp = GetXmlHttpObject(); if

(!xmlHttp)

154
{ return false; }

xmlHttp.onreadystatechange = function()

if (xmlHttp.readyState == 4)

{ alert("Request complete");

var requestURI = "http://myserver.org/somepage.txt";

xmlHttp.open("GET" , requestURI, true);

xmlHttp.send(null);

4.8.7 The XMLHTTPRequest Object


• An XMLHTTPRequest object is in one of 5 states, as indicated by the readyState property

0. The request is not initializedThe request has been set up

1. The request has been sent

2. The request is in process

3. The request is complete

• Every time the readyState property changes the onreadystatechange property (a function) is called

4.8.8 Setting onreadystatechange


function sendRequest()

var xmlHttp = GetXmlHttpObject();

if (!xmlHttp) { return false; }

xmlHttp.onreadystatechange = function()

{ if (xmlHttp.readyState == 4)

{ alert("Request complete"); }

var requestURI =

155
"http://myserver.org/somepage.txt";

xmlHttp.open("GET" , requestURI, true);

xmlHttp.send(null);

4.8.9 The open and send functions


• The open function of an XML HTTP request takes three arguments

– xmlHttp.open(method, uri, async)

– method is either "GET" or "POST"

– uri is the (relative) URI to retrieve

– async determines whether to send the request asynchronously (true) or synchronously


(false)

– The domain of the uri argument must be the same as the domain of the current page

• The send function takes one argument

– xmlHttp.send(content);

– content is the content to send (useful when method= "POST")

Sending the Request


function sendRequest()

var xmlHttp =

GetXmlHttpObject(); if

(!xmlHttp) { return false; }

xmlHttp.onreadystatechange = function()

{ if (xmlHttp.readyState == 4) { alert("Request

complete"); } } var requestURI =

"http://myserver.org/somepage.txt"; xmlHttp.open("GET"

, requestURI, true);

xmlHttp.send(null);

156
The responseText Property
• When an XMLHTTPRequest is complete (readyState == 4) the responseText property contains the
server's response, as a String.

Example Code (Client Side)


function sendRequest(textNode)

var xmlHttp = GetXmlHttpObject(); if

(!xmlHttp) { return false; }

xmlHttp.onreadystatechange = function()

{ if (xmlHttp.readyState == 4)

{ textNode.nodeValue = xmlHttp.responseText; } }

var requestURI = "http://greatbeyond.org/cgi-

bin/request.cgi"; xmlHttp.open("GET" , requestURI,

true);

xmlHttp.send(null);

Example Code (Server Side)


And we might have the following request.cgi in the cgi-bin directory of

greatbeyond.org#!/usr/bin/perl

print("Content-type:

text/plain\n\n"); print("57

channels and nuthin' on");

Respond with XML

 We can look at the XML text within a response using the responseText property
 Even better, we can use the responseXML property to access the XML
 Best, responseXML.documentElement contains the document tree for the XML
 This is a document tree in the DOM model that we've seen before (just like document)

Example
function sendRequest() {

157
var xmlHttp = GetXmlHttpObject(); if

(!xmlHttp) { return false; }

xmlHttp.onreadystatechange = function() { if

(xmlHttp.readyState == 4) {

var xmlDoc = xmlHttp.responseXML.documentElement;

}}

var requestURI = xmlURI;

xmlHttp.open("GET" , requestURI, true);

xmlHttp.send(null);

}
4.9 Jquery Selectors
jQuery selectors allow you to select and manipulate HTML element(s).

jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it
has some own custom selectors.

All selectors in jQuery start with the dollar sign and parentheses: $().

The element Selector

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example

When a user clicks on a button, all <p> elements will be


hidden:

Example

$(document).ready(function(){

$("button").click(function(){

$("p").hide();

158
});

});

Fig-4.3 output of Jquey Selectors

Fig-4.4 output of Jquey Selectors

4.10 Adding and Removing Elements with Jquery.


Add New HTML Content

We will look at four jQuery methods that are used to add new content:

append() - Inserts content at the end of the selected elements

prepend() - Inserts content at the beginning of the selected elements

after() - Inserts content after the selected elements

before() - Inserts content before the selected elements

jQuery append() Method

The jQuery append() method inserts content AT THE END of the


selected HTML elements.

Example

<!DOCTYPE html>

<html>

<head>

<script

159
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"><
/script>

<script>

$(document).ready(function(){

$("#btn1").click(function(){

$("p").append(" <b>Appended text</b>.");

});

$("#btn2").click(function(){

$("ol").append("<li>Appended item</li>");

});

});

</script>

</head>

<body>

<p>This is a paragraph.</p>

<p>This is another paragraph.</p>

<ol>

<li>List item 1</li>

<li>List item 2</li>

<li>List item 3</li>

</ol>

<button id="btn1">Append text</button>

<button id="btn2">Append list items</button>

</body>

160
</html>

Remove Elements/Content

To remove elements and content, there are mainly two jQuery methods:

remove() - Removes the selected element (and its child elements)

empty() - Removes the child elements from the selected element

jQuery remove() Method

The jQuery remove() method removes the selected element(s) and its child
elements.

Example

<!DOCTYPE html>

<html>

<head>

<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

161
$("button").click(function(){

$("#div1").remove();

});

});

</script>

</head>

<body>

<div id="div1" style="height:100px;width:300px;border:1px solid


black;background-color:yellow;">

This is some text in the div.

<p>This is a paragraph in the div.</p>

<p>This is another paragraph in the div.</p>

</div>

<br>

<button>Remove div element</button>

</body>

</html>

4.11 Ajax with Jquery.


AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load

162
data from the server without a browser page refresh.

If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding
further.

JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web
application.

Loading Simple Data

This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to
do the job −

Syntax

Here is the simple syntax for load() method −

[selector].load( URL, [data], [callback] );

Here is the description of all the parameters −

URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP
script which generates data dynamically or out of a database.

data − This optional parameter represents an object whose properties are serialized into properly encoded
parameters to be passed to the request. If specified, the request is made using the POST method. If
omitted, the GET method is used.

callback − A callback function invoked after the response data has been loaded into the elements of the
matched set. The first parameter passed to this function is the response text received from the server and
second parameter is the status code.

Example

Consider the following HTML file with a small JQuery coding −

<html>

<head>

<title>The jQuery Example</title>

<script type = "text/javascript"

src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">

</script>

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

$(document).ready(function() {

$("#driver").click(function(event){

$('#stage').load('/jquery/result.html');

});

});

</script>

</head>

<body>

<p>Click on the button to load /jquery/result.html file −</p>

<div id = "stage" style = "background-color:cc0;">

STAGE

</div>

<input type = "button" id = "driver" value = "Load Data" />

</body>

</html>

Here load() initiates an Ajax request to the specified URL /jquery/result.html file.
After loading this file, all the content would be populated inside <div> tagged with
ID stage. Assuming, our /jquery/result.html file has just one HTML line −

<h1>THIS IS RESULT...</h1>

When you click the given button, then result.html file gets loaded.

Fig-4.3 output of Jquey

164
4.12 Animation with Jquery
jQuery Animations - The animate() Method

The jQuery animate() method is used to create custom animations.

Syntax:

$(selector).animate({params},speed,callback);

The required params parameter defines the CSS properties to be animated.

The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or
milliseconds.

The optional callback parameter is a function to be executed after the animation


completes. The following example demonstrates a simple use of the animate()
method; it moves a <div> element to the right, until it has reached a left property of
250px:

<!DOCTYPE html>

<html>

<head>

<script
src="https://ajax.googleapis.com/ajax/libs/j
query/3.5.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

$("button").click(function(){

$("div").animate({left: '250px'});

});

});

</script>

</head>

<body>

<button>Start Animation</button>

165
<p>By default, all HTML elements have a static position, and cannot be moved. To manipulate
the position, remember to first set the CSS position property of the element to relative, fixed, or
absolute!</p>

<div
style="background:#98bf21;height:100px;
width:100px;position:absolute;"></div>

</body>

</html>

Fig-4.4 output of Animation with Jquey

Summary
 Know the concepts of JavaScript
 Detail Learn about JSON
 Learn the concepts of AJAX
 Learn about JQuery
Keywords
Composite Types. An object is a composite type that can contain primitive and composite types an
object is a collection that can contain primitive or composite data, including functions and other
objects. The data members of an object are called properties, and member functions are known as
methods.
Self-Assessment QuestionsFurther Readings
DOM: Document Object Model (DOM) is a set of platform independent and language neutral
application interface (API) which describes how to access and manipulate the information stored in

166
XML, XHTML and JavaScript documents.
Event Handler: An event handler typically is a software routine that processes actions such as
keystrokes and mouse movements. With Web sites, event handlers make Web content dynamic.
JavaScript is a common method of scripting event handlers for Web content.

JQuery Function: The jQuey function is the value of jQuery or of $. This is the function that creates
JQuery objects, registers handlers to be invoked when the DOM is ready, and that
also serves as the jQuery namespace
Ajax: Ajax is a set of client side technologies that provides asynchronous communication between user
interfaces and web server. So the advantages of using Ajax are asynchronous communication,
minimal data transfer and server is not overloaded with unnecessary load.
Animating the canvas: Animation involves repeatedly clearing the canvas and drawing an image on it.
To create smooth animations, you need to minimize the time between clearing the canvas and
completing the new drawing, and you need to keep the changes relatively small from image to image.
SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What is meant by statements in Javascript?
2. What is meant by identifiers?
3. Define Operators in JavaScript.
4. How many looping structures can you find in javascript?
5. Mention The Various Java Script Object Models.
6. Define media queries.
7. What is meant by JqueryObject?
8. What technologies are being used in AJAX?
Long Answer Questions
1. Explain the core features of JavaScript in detail.
2. Explain the primitive data types used in JavaScript?
3. Explain the storage concepts in detail
4. How to add and remove elements from JQuery?
5. Explain the concepts of AJAX with example.
6. Explain Animations with jQuery.
FURTHER READINGS
1. Harvey & Paul Deitel & Associates, Harvey Deitel and Abbey Deitel, ―Internet and World Wide Web
- How to Program‖, Fifth Edition, Pearson Education, 2011.
2.David Flanagan, ―JavaScript: The Definitive Guide‖, 7th Edition. O Reilly Publications.2020

167
UNIT-V – Server-Side Programming with PHP

CONTENTS
Learning Objectives

Learning OutcomesOverview
5.1 PHP Basics
5.2 PHP Variables
5.3 PHP Program control

5.4 PHP-Arrays

5.5 PHP User Defined Function

5.6 File Handling with PHP

5.7 Cookies

5.8 Working with WAMP and PHPADMIN

5.9 Establishing with MYSQL using PHP

LEARNING OBJECTIVES

After studying this lesson, you should be able to:


 Illustrate PHP basic Syntax
 Understand the different types of File Handling
 Learn about cookies
 Establishing connectivity with MYSQL using PHP

LEARNING OUTCOMES
Upon completion of the lesson, students can demonstrate a good understanding of:
 To learn the PHP basic concepts
 Know about the Different types of File Handling
 Analyzing PHP cookies.

168
 Concept of connectivity with MYSQL with PHP.

5.1 PHP Basics


PHP (Hypertext Preprocessor):
An Introduction to PHP:
 PHP is a server-side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites
 PHP performs system functions, i.e., from files on a system it can create, open, read, write, and close
them. The other uses of PHP are:
o PHP can handle forms, i.e., gather data from files, save data to a file, thru email you can send data,
return data to the user.
o You add, delete, modify elements within your database thru PHP.
o Access cookies variables and set cookies.
o Using PHP, you can restrict users to access some pages of your website.
o It can encrypt data.
 PHP is embedded in HTML. That means that in amongst your normal HTML you will have PHP
statements.

<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>

It will produce the following result:

Hello, World!

PHP is a simple, yet powerful language designed for creating HTML content. This unit covers
essential background on the PHP language. It describes the nature and history of PHP, which
platforms it runs on, and how to configure it. This unit ends by showing you PHP in action, with
a quick walkthrough of several PHP programs that illustrate common tasks, such as processing
form data, interacting with a database and creating graphics.
PHP can be used in three primary ways:
Server-side Scripting
PHP was originally designed to create dynamic web content, and it is still best suited for that
task. To generate HTML, you need the PHP parser and a web server through which to send the
coded documents. PHP has also become popular for generating XML documents, graphics, Flash

169
animations, PDF files, and so much more.

Command-line Scripting
PHP can run scripts from the command line, much like Perl, awk, or the Unix shell. You might
use the command-line scripts for system administration tasks, such as backup and log parsing.
even some CRON job type scripts can be done this way (nonvisual PHP tasks).
Graphical Scripting
Using PHP-GTK, you can write full-blown, cross-platform GUI applications in PHP. In this
book, however, we concentrate on the first item: using PHP to develop dynamic web content.
PHP runs on all major operating systems, from Unix variants including Linux, FreeBSD, Ubuntu,
Debian, and Solaris to Windows and Mac OS X. It can be used with all leading web servers,
including Apache, Microsoft IIS, and the Netscape/iPlanet servers.
Notes The language itself is extremely flexible.

5.1.2 Syntax Overview:


Commenting PHP Code: A comment is the portion of a program that exists only for the human reader
and stripped out before displaying the programs result. There are two commenting formats in PHP:
1. Single-line comments: (//…)They are generally used for short explanations or notes relevant to the local
code.
2. Multi-lines comments:( /*..*/)They are generally used to provide pseudocode algorithms and more
detailed explanations when necessary

PHP is whitespace insensitive: PHP whitespace insensitive means that it almost never matters how
many whitespace characters you have in a row.one whitespace character is the same as many such
characters.
PHP is case sensitive: PHP is a case sensitive language. In PHP, all keywords (e.g. if, else, while,
echo, etc.), classes, functions, and user-defined functions are NOT case-sensitive.
Example:
<html>
<body>
<?
$capital = 67;
print("Variable capital is $capital<br>");
print("Variable CaPiTaL is $CaPiTaL<br>");
?>
</body>
</html>
This will produce the following result:
Variable capital is 67
Variable CaPiTaL is

Statements are expressions terminated by semicolons: A statement in PHP is any expression that is
followed by a semicolon (;).Any sequence of valid PHP statements that is enclosed by the PHP tags is a

170
valid PHP program.

5.2 PHP Variable:


A variable in PHP is a name of memory location that holds data. A variable is a temporary storage that
is used to store data temporarily.

 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and the expression
to be evaluated on the right.
· Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when necessary.

PHP has a total of eight data types which we use to construct our variables:

 Integers: are whole numbers, without a decimal point, like 4195.


 Doubles: are floating-point numbers, like 3.14159 or 49.1.
 Booleans: have only two possible values either true or false.
 NULL: is a special type that only has one value: NULL.
 Strings: are sequences of characters, like 'PHP supports string operations.'
 Arrays: are named and indexed collections of other values.
 Objects: are instances of programmer-defined classes, which can package up both other kinds of
values and functions that are specific to the class.
 Resources: are special variables that hold references to resources external to PHP (such as database
connections).
Syntax
$variablename=value;
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!, the
variable $x will hold the value 5, and the variable $y will hold the value 10.5.

5.3 PHP Program Control:


Code execution can be grouped into categories as shown below
 Sequential – this one involves executing all the codes in the order in which they have been written.
 Decision – this one involves making a choice given a number of options. The code executed depends
on the value of the condition.
A control structure is a block of code that decides the execution path of a program depending on the
value of the set condition.
5.3.1 IF Else:
If… then... else is the simplest control structure. It evaluates the conditions using Boolean logic

171
When to use if… then… else
Syntax
<?php
if (condition is true) {
block one
else
block two
}
?>
Example
<?php
$first_number = 7;
$second_number = 21;
if ($first_number > $second_number){
echo "$first_number is greater than $second_number";
}else{
echo "$second_number is greater than $first_number";
}
?>
This will produce the following result:
21 is greater than 7

5.3.2 PHP Switch Case:

Switch… case is similar to the if then… else control structure.


It only executes a single block of code depending on the value of the condition.
If no condition has been met then the default block of code is executed.

Syntax:
<?php
switch(condition){
case value:
//block of code to be executed
break;
case value2:
//block of code to be executed
break;
default:
//default block code
break;
}
?>

Example:
<?php
$today = "wednesday";
switch($today){
case "sunday":
echo "pray for us sinners.";
break;

172
case "wednesday":
echo "ladies night, take her out for dinner";
break;
case "saturday":
echo "take care as you go out tonight.";
break;
default:
echo "have a nice day at work";
break;
}
?>

This will produce the following result:


ladies night, take her out for dinner

5.3.4 PHP For Loop:


There are basically two types of for loops;
 for
 for… each.
Syntax:
<?php
for (initialize; condition; increment){
//code to be executed
}
?>

Example:
<?php
for ($i = 0; $i < 10; $i++){
$product = 10 * $i;
echo "The product of 10 * $i is $product <br/>";
}
?>

This will produce the following result:


The product of 10 x 0 is 0
The product of 10 x 1 is 10
The product of 10 x 2 is 20
The product of 10 x 3 is 30
The product of 10 x 4 is 40
The product of 10 x 5 is 50
The product of 10 x 6 is 60
The product of 10 x 7 is 70
The product of 10 x 8 is 80
The product of 10 x 9 is 90

5.3.5 PHP For Each loop


The php foreach loop is used to iterate through array values

173
Syntax:
<?php
foreach($array_variable as $array_values){
block of code to be executed
}
?>
Example:
<?php
$animals_list = array("Lion","Wolf","Dog","Leopard","Tiger");
foreach($animals_list as $array_values){
echo $array_values . "<br>";
}
?>
Output:
Lion
Wolf
Dog
Leopard
Tiger

5.3.6 PHP While loop


 They are used to execute a block of code a repeatedly until the set condition gets satisfied.
 While loops are used to execute a block of code until a certain condition becomes true.
 You can use a while loop to read records returned from a database query.

Types of while loops


Do… while - executes the block of code at least once before evaluating the condition
While… - checks the condition first. If it evaluates to true, the block of code is executed as long as
the condition is true. If it evaluates to false, the execution of the while loop is terminated.
Syntax:

<?php
while (condition){
block of code to be executed;
}
?>

Example:
<?php
$i = 0;
while ($i < 5){
echo $i + 1 . "<br>";
$i++;
}
?>
Output:
1
2

174
3
4
5
5.3.7 PHP Do While
The difference between While… loop and Do… while loop is do… while is executed at-least once before
the condition is evaluated.

Syntax:
<?php
do{
block of code to be executed
}
?>

Example:
<?php
$i = 9;
do{
echo "$i is"." <br>";
}
while($i < 9);
?>
Outputs:
9

5.3.8 Built-in Functions:


Built in functions are functions that exist in PHP installation package.

The built in functions can be classified into many categories.


 PHP Array Functions
 PHP Calender Functions
 PHP Class/Object Functions
 PHP Character Functions
 PHP Date & Time Functions
 PHP Directory Functions
 PHP Error Handling Functions
 PHP File System Functions
 PHP MySQL Functions
 PHP Network Functions
 PHP ODBC Functions
 PHP String Functions
 PHP SimpleXML Functions
 PHP XML Parsing Functions

5.4 PHP – Arrays:


An array is a data structure that stores one or more similar type of values in a single value.

175
Create an Array in PHP:

In PHP, the array() function is used to create an array:

array();
Three different kind of arrays:
 Numeric array − An array with a numeric index. Values are stored and accessed in linear
fashion.

 Associative array − An array with strings as index. This stores element values in association
with key values rather than in a strict linear index order.

 Multidimensional array − An array containing one or more arrays and values are accessed
using multiple indices

5.4.1 Numeric Array


These arrays can store numbers, strings and any object but their index will be represented by numbers.
By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.

Here we have used array() function to create array. This function is explained in function reference.

<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
foreach( $numbers as $value ) {
echo "Value is $value <br />";
}

/* Second method to create array. */


$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";

foreach( $numbers as $value ) {


echo "Value is $value <br />";
}
?>
</body>
</html>

Output:
Value is 1

176
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
5.4.2 Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you can
establish a strong association between key and values.

Example
<html>
<body>

<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" => 500);

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";

/* Second method to create array. */


$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium";
$salaries['zara'] = "low";

echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />";


echo "Salary of qadir is ". $salaries['qadir']. "<br />";
echo "Salary of zara is ". $salaries['zara']. "<br />";
?>

</body>
</html>

Output:
Salary of mohammad is 2000
Salary of qadir is 1000
Salary of zara is 500
Salary of mohammad is high
Salary of qadir is medium
Salary of zara is low

5.4.3 Multidimensional Arrays


A multi-dimensional array each element in the main array can also be an array. And each element in
the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using

177
multiple index.

Example
In this example we create a two-dimensional array to store marks of three students in three subjects −

This example is an associative array, you can create numeric array in the same fashion.

<html>
<body>
<?php
$marks = array(―mohammad" => array ("physics" => 35,"maths" => 30,"chemistry" => 39),
"qadir" => array ( "physics" => 30,"maths" => 32, "chemistry" => 29),
"zara" => array ("physics" => 31,"maths" => 22,"chemistry" => 39 ));

/* Accessing multi-dimensional array values */


echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for qadir in maths : ";
echo $marks['qadir']['maths'] . "<br />";
echo "Marks for zara in chemistry : " ;
echo $marks['zara']['chemistry'] . "<br />";
?>

</body>
</html>

Output:
Marks for mohammad in physics : 35
Marks for qadir in maths : 32
Marks for zara in chemistry : 39
5.5 PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.

Create a User Defined Function in PHP


A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function

178
?>
PHP Functions with Parameters
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters
your like. These parameters work like variables inside your function.

Example
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
Output:
Sum of the two numbers is : 30

5.6 File Handling with PHP

File Handling in PHP

5.6.1 Opening and Closing Files


Files are opened in PHP using the fopen command. The command takes two parameters, the file
to be opened, and the mode in which to open the file. The function returns a file pointer if
successful, otherwise zero (false). Files are opened with fopen for reading or writing.

$fp = fopen("myfile.txt", "r");

If fopen is unable to open the file, it returns 0. This can be used to exit the function with an
appropriate message.

if ( !($fp = fopen("myfile.txt", "r") ) ) exit("Unable to


open the input file.");

5.6.2 File Modes


The following table shows the different modes the file may be opened in.

179
Table 5.1 File Mode

Mode Description

r Read Only mode, with the file pointer at the start of the file.

r+ Read/Write mode, with the file pointer at the start of the file.

w Write Only mode. Truncates the file (effectively overwriting it). If the file doesn't exist,
fopen will attempt to create the file.
w+
Read/Write mode. Truncates the file (effectively overwriting it). If the file doesn't exist,
fopen will attempt to create the file.
a
Append mode, with the file pointer at the end of the file. If the file doesn't exist, fopen
a+ will attempt to create the file.

Read/Append, with the file pointer at the end of the file. If the file doesn't exist, fopen
will attempt to create the file.

Note: The mode may also contain the letter 'b'. This is useful only on systems which differentiate
between binary and text files (i.e. Windows. It's useless on Unix/Linux). If not needed, it will be
ignored.

5.6.3 Closing a File

The fclose function is used to close a file when you are finished with it.fclose($fp);

5.6.4 Reading from Files

You can read from files opened in r, r+, w+, and a+ mode. The feof function is used to determine
if the end of file is true.

if ( feof($fp) )
echo "End of file<br>";

The feof function can be used in a while loop, to read from the file until the end of file is
encountered. A line at a time can be read with the fgets function:

while( !feof($fp) ) {
// Reads one line at a time, up to 254 characters. Each line ends with a newline.
// If the length argument is omitted, PHP defaults to a length of 1024.
$myline = fgets($fp, 255);echo
$myline;
}

You can read in a single character at a time from a file using the fgetc function:

while( !feof($fp) ) {

180
// Reads one character at a time from the file.
$ch = fgetc($fp); echo
$ch;
}

You can also read a single word at a time from a file using the fscanf function. The function
takes a variable number of parameters, but the first two parameters are mandatory. The first
parameter is the file handle, the second parameter is a C-style format string. Any parameters
passed after this are optional, but if used will contain the values of the format string.

$listFile = "list.txt"; // See next page for file contentsif


(!($fp = fopen($listFile, "r")))
exit("Unable to open $listFile."); while
(!feof($fp)) {
// Assign variables to optional arguments
$buffer = fscanf($fp, "%s %s %d", $name, $title, $age);
if ($buffer == 3) // $buffer contains the number of items it was able to assignprint
"$name $title $age<br>\n";
}

Here is the file list.txt:


Dave Programmer 34
Sue Designer 21
Lisa Programmer 29
Nigel User 19

You can also store the variables in an array by omitting the optional parameters in fscanf:while
(!feof($fp)) {
$buffer = fscanf($fp, "%s %s %d"); // Assign variables to an array
// Use the list function to move the variables from the array into variables
list($name, $title, $age) = $buffer;
print "$name $title $age<br>\n";
}

You can read in an entire file with the fread function. It reads a number of bytes from a file, up
to the end of the file (whichever comes first). The filesize function returns the size of the file in
bytes, and can be used with the fread function, as in the following example.
$listFile = "myfile.txt";
if (!($fp = fopen($listFile, "r")))
exit("Unable to open the input file, $listFile.");
$buffer = fread($fp, filesize($listFile)); echo
"$buffer<br>\n";
fclose($fp);

You can also use the file function to read the entire contents of a file into an array instead of
opening the file with fopen:
$array = file(‗filename.txt‘);

Each array element contains one line from the file, where each line is terminated by a newline.

181
5.6.5 Writing to Files
The fwrite function is used to write a string, or part of a string to a file. The function takes three
parameters, the file handle, the string to write, and the number of bytes to write. If the number of
bytes is omitted, the whole string is written to the file. If you want the lines to appear on separate
lines in the file, use the \n character. Note: Windows requires a carriage return character as well as
a new line character, so if you're using Windows, terminate the string with \r\n. The following
example logs the visitor to a file, then displays all the entries in the file.

<?php
$logFile = "stats.txt";
$fp = fopen($logFile, "a+"); // Open the file in append/read mode
$userDetails = $_SERVER[‗HTTP_USER_AGENT‘]; // Create a string containing user
detailsif (isset($_SERVER[‗HTTP_REFERER‘]))
$userDetails .= " {$_SERVER[‗HTTP_REFERER‘]}<br>\r\n";
else
$userDetails .= "<br>\r\n";
fwrite($fp, "$userDetails"); // Write the user details to the file
rewind($fp); // Move the file pointer to the start of the file
$entries = 0;
while(!feof($fp)) { // Display each line in the file
$buffer = fgets($fp, 1024);if
($buffer != "") {
echo $buffer;
$entries++;
}
} // Show a summary
echo "There are $entries entries in the log file<br>";
fclose ($fp);
?>

5.6.6 Locking Files


boolean flock ( resource fp, integer operation)
PHP supports a portable way of locking complete files in an advisory way (which means all
accessing programs have to use the same way of locking or it will not work). If there is a
possibility that more than one process could write to a file at the same time, then the file
shouldbe locked.

flock() operates on fp which must be an open file pointer. operation is one of the following:
 To acquire a shared lock (reader), set operation to LOCK_SH
 To acquire an exclusive lock (writer), set operation to LOCK_EX
 To release a lock (shared or exclusive), set operation to LOCK_UN
 If you don't want flock() to block while locking, add LOCK_NB to LOCK_SH or LOCK_EX

When obtaining a lock, the process may block. That is, if the file is already locked, it will wait
until it gets the lock to continue execution. flock() allows you to perform a simple
reader/writer model which can be used on virtually every platform (including most Unix
derivatives and even Windows). flock() returns TRUE on success and FALSE on error (e.g.

182
when a lock could not beacquired).

Here is a script that writes to a log file with the fputs function and then displays the log file‘s
contents:

<?php
$fp = fopen(―/tmp/log.txt‖, ―a‖);
flock($fp, LOCK_EX); // get lock
fputs($fp, date(―h:i A l F dS, Y\n‖)); // add a single line to the log file
flock($fp, LOCK_UN); // release lock
fclose($fp);
echo ―<pre>‖; // dump log
readfile(―/tmp/log.txt‖);
echo ―</pre>\n‖;
?>

5.6.7 Other Useful File Functions


The opendir function returns a directory handle; closedir closes a directory; readdir reads a
directory entry.

$myDirectory = opendir(―.‖); // use the current directory


while($entryname = readdir($myDirectory)) {
echo ―<tr>‖;
echo ―<td>$entryname</td>‖;
echo ―<td align=\‖right\‖>‖;
echo filesize($entryname); // the filesize function returns the file size in bytes
echo ―</td>‖;
echo ―</tr>\n‖;
}
closedir($myDirectory);

The is_dir function tests if a filename refers to a directory:

if(is_dir($filename))
echo $filename . ― is a directory‖;

The is_file function determines if a filename refers to a file:

if(is_file($filename))
echo $filename . ― is a file‖;

The is_readable function returns TRUE if the file exists and it is readable, otherwise it
returns false. On Unix/Linux this is determined by the file‘s permissions. On Windows,
TRUE is always returned if the file exists.

if(is_readable($filename))
echo $filename . ― is readable‖;

183
The is_writable function determines whether the server will allow you to write data to
the filebefore you attempt to open it:

if(is_writable(‗../quotes.txt‘)) {
// attempt to open the file and write to it
} else {
echo ‗The file is not writable‘;
}

5.7 Using Cookies:


Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.

5.7.1 Three Types:


 Server script sends a set of cookies to the browser. For example name, age, or identification
number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
5.7. 2 Setting Cookies with PHP:

PHP provided setcookie() function to set a cookie. This function requires upto six arguments
and should be called before <html> tag. For each cookie this function has to be called
separately.

setcookie(name, value, expire, path, domain, security);

Detail of all the arguments:


 Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
 Value − This sets the value of the named variable and is the content that you actually want to
store.
 Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this
time cookie will become inaccessible. If this parameter is not set then cookie will automatically
expire when the Web Browser is closed.
 Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
 Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
 Security − This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

Example will create two cookies name and age these cookies will be expired after one hour.

<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);

184
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>

<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

5.7.3 Accessing Cookies with PHP

PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above
example.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
</body>
</html>

You can use isset() function to check if a cookie is set or not.

<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>

5.7.4 Deleting Cookie with PHP


Officially, to delete a cookie you should call setcookie() with the name argument only but this does

185
not always work well, however, and should not be relied on.

It is safest to set the cookie with a date that has already expired −

<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
5.8 Working with WAMP AND phpadmin

WAMP Server is a server which is used to host PHP pages. PHP is a server-side scripting language
developed by Rasmus Lerdorf.

WAMP stands for – Window Apache MySQL and PHP.

Developed by – Romain Bourdon

Operating system – Windows

Now we are going to discuss the steps for WAMP Server Installation.

Step 1:

WAMP Server download

In this website download WAMP Server 32 BITS & PHP 5.6.15.

On clicking the download link, the following window will open for download. In this click the
following.

186
Figure 5. 1: Direct link to download

After clicking that link the following downloading process window will open.

Figure 5.2: Downloading Window.

Now your file is downloaded and save that *.exe file in your system drive location.

Figure 5.3: Save the file

187
After the file has downloaded the following tray icon file is visible and stored at your system location

Figure 5.4

Step 2:

Now double click that exe file.

The following window will open

Figure 5.5: Security warning window for running process

Click Run button and the installation process window will open. First you have to choose the language
default as English and then hit ok. Then the step up process wizard will open. In that window click Next
button to proceed the installation.

Then the License agreement window will open, click I accept the agreement and then hit next. Next the
set up information window will open, then hit next.

The destination location window will open to save where the WAMP folder wants to be located. By
default it takes C:\wamp, then hit next and then Install button to install the WAMP Server.

188
Figure 5.6: Installation processed window.

After installation click finish button to navigate WAMP Server.

Now the orange color try Icon placed at the start menu is visible.

Figure 5.7: Tray Icon in orange color

The tray icon is visible in orange because there are two applications running at localhost using same port
number, like 80. Left click the tray Icon, select local host and it shows the following window IIS.

If you face the error, then click the link to download the file (VCRUNTIME140.dll) as shown below and
paste it into C:\Windows folder

api-ms-win-crt-runtime-l1-1-0.dll (cannot start error means)

189
Figure 5.8

Figure 5.9: IIS7

So now we are going to stop IIS port 80 or we could change the WAMPSERVER LISTEN PORT value
80 to 81 in the following way.

Left click the tray Icon and do the following steps

Figure 5.10: httpd.conf

After selecting httpd.conf file one notepad window will open and search the text Listen by using
CTRL+F.

190
Figure 5.11: Listen Port

Here change the listen portfrom 80 to 81.

Right click the tray Icon and choose refresh then left click the icon restart all services. Now your tray
icon turned to green. WAMP Server is now ready.

Now left click the icon and choose localhost

The IIS logo window will open in your browser. In your address bar near your localhost mention the
following like localhost:81, then the window will appear in the following manner.

Figure 5.12: WAMP SERVER home page

191
Step 3:

After installation is completed host a simple PHP website via WAMPSERVER. The following steps to be
noted.

The folder of wampis placed into your C:\wamp system location.

In this wamp folder navigate to www root folder and there two files appear; one is index.php and another
one is testmysql.php those files are built-in type files.

Now we have to place our sample website folder into that www root directory like the following:

Figure 5.13: Place website folder into www root directory

Now refresh our localhost in browser and we find our sample website appears under projects title.

Figure 5.14: Projects

Now click that folder in our browser and our sample project home page will open like this

192
Figure 15: Sample website home page.

Step: 4

Before you create your database in SQL server try to backup the file in *.sql format. In your WAMP
Server home page PhpMyAdmin link appears. Click that link and the database connectivity form will
open in the following format.

Figure 5.16: PHP my admin page

Set the username as root and make empty password column and hit go. The admin page window will
open like the following,

Figure 5.17: php my admin database connectivity page

193
After the page opens in your right side window, click database and choose to create database.

Figure 5.18: Database creativity

Now your database will present at left side php mydmin page,

Figure: 5.19

Choose your database and create table or you have to restore your SQL database.
Restore SQL Server database in the following format.

Click import link the following window will open

194
Figure 5.20: Import Database

In this window browse your *.sql backup file, choose character set and then hit Go button it takes some
time to import so please be patient until the database is imported.

After importing you will get the following message box:

Figure 5.21: Importing successful window.

Now your website is ready to connect the database and now browse your site in localhost:81

Enter your username and password and then hit to login,

195
Figure5. 22: Login page

5.9 Establishing with MYSQL using PHP


PHP offers built-in support for many databases.

PHP will work with virtually all database software, including Oracle and Sybase but most used is freely
available MySQL database.
 Connecting to MySQL database − Use PHP to open and close a MySQL database connection.

 Create MySQL Database Using PHP − To create MySQL database and tables using PHP.

 Delete MySQL Database Using PHP − To delete MySQL database and tables using PHP.

 Insert Data to MySQL Database − Once you have created your database and tables then you would
like to insert your data into created tables.

 Retrieve Data from MySQL Database − To fetch records from MySQL database using PHP.

 Using Paging through PHP – To show your query result into multiple pages and how to create the
navigation link.

 Updating Data into MySQL Database − To update existing records into MySQL database using PHP.

 Deleting Data from MySQL Database − To delete or purge existing records from MySQL database
using PHP.
Opening Database Connection
PHP provides MySQL connect function to open a database connection. This function takes five parameters and returns a
MySQL link identifier on success, or FALSE on failure.
Syntax
connection mysql_connect(server,user,passwd,new_link,client_flag);
Closing Database Connection
Its simplest function mysql_close PHP provides to close a database connection. This function takes connection resource
returned by mysql_connect function. It returns TRUE on success or FALSE on failure.
Syntax
bool mysql_close ( resource $link_identifier );

196
If a resource is not specified then last opend database is closed.

Example
Try out following example to open and close a database connection −

<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
Creating a Database
To create and delete a database you should have admin privilege. Its very easy to create a new MySQL
database. PHP uses mysql_query function to create a MySQL database. This function takes two
parameters and returns TRUE on success or FALSE on failure.

Syntax
bool mysql_query( sql, connection );

Example

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE Database test_db';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create database: ' . mysql_error());
}
echo "Database test_db created successfully\n";
mysql_close($conn);
?>
Selecting a Database
Once you establish a connection with a database server then it is required to select a particular database
where your all the tables are associated.

197
This is required because there may be multiple databases residing on a single server and you can do work
with a single database at a time.

PHP provides function mysql_select_db to select a database.It returns TRUE on success or FALSE on
failure.

Syntax
bool mysql_select_db( db_name, connection );

Example
<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db( 'test_db' );
mysql_close($conn);
?>
Creating Database Tables
To create tables in the new database you need to do the same thing as creating the database. First create the
SQL query to create the tables then execute the query using mysql_query() function.

Example
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$sql = 'CREATE TABLE employee( '.
'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_name VARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_date timestamp(14) NOT NULL, '.
'primary key ( emp_id ))';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );

if(! $retval ) {
die('Could not create table: ' . mysql_error());

198
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $ sql variable and excute those commands.

Consider the following content in sql_query.txt file

CREATE TABLE employee(


emp_id INT NOT NULL AUTO_INCREMENT,
emp_name VARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_date timestamp(14) NOT NULL,
primary key ( emp_id ));

<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'root password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$query_file = 'sql_query.txt';
$fp = fopen($query_file, 'r');
$sql = fread($fp, filesize($query_file));
fclose($fp);
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table employee created successfully\n";
mysql_close($conn);
?>
Summary
 Know the concepts of PHP Basics
 Detail Learn PHP Variables
 Learn the File Handling with PHP
 Learn about Cookies
 Learn about the establish connectivity with MYSQL using PHP

199
Keywords

LAMP: LAMP stack is a group of open source software used to get web servers up and running. The acronym
stands for Linux, Apache, MySQL, and PHP.
Arrays: Arrays are complex variables that store a group of values under a single variable name. An array
is useful for storing a group of related values. In PHP arrays are nothing but group of key/value
associations under a single array name. The keys can be either numeric or text. Depending on the type of
key, the arrays are classified as Numeric Arrays (Keys are numbers), Associative Arrays (Keys are
strings) Composite Types. An object is a composite type that can contain primitive and composite types
an object is a collection that can contain primitive or composite data, including functions and other
objects. The data members of an object are called properties, and member functions are known as
methods.
MySQL: MYSQL is a relational database management system (RDBMS) that runs as a server providing
multi-user access to a number of databases. The official MySQL Workbench is a free integrated
environment developed by MySQL AB that enables users to graphically administer MySQL databases
and visually design database structure.

Embedding PHP within HTML.: PHP script may be embedded within HTML documents ie meaning PHP
and HTML code can both happily co-exist in the same file. All embedded PHP code must be contained
within<?php and?> tags so it can be readily recognized by the PHP engine for interpretation. Typically the
PHP code will write content into the body section of the html document. This is then sent to web browser.

200
SELF-ASSESSMENT QUESTIONS
Short Answer Questions
1. What is PHP?
2. What is meant by LAMP server?
3. What are the steps to set a LAMP server?
4. What is a PHP File?
5. What is the difference between Print and Echo Statements?
6. Define Variables in PHP.
7. What are the Operators available in PHP?
8. Define MYSQL.
9. What are the software components in LAMP?
10. What is meant by cookies?
Long Answer Questions
1. Explain the setting up the environment for LAMP server.
2. Explain variables and constants with examples.
3. Explain String and array concepts with examples Explain the core features of JavaScript in detail.
4. Explain the different types of operators in php with example program.
5. Explain Establish connectivity with MYSQL database,
6. Explain File Handling with examples.
7. Explain the concepts of Cookies.

FURTHER READINGS
1. Harvey & Paul Deitel & Associates, Harvey Deitel and Abbey Deitel, ―Internet and World Wide Web
- How to Program‖, Fifth Edition, Pearson Education, 2011.
2. Robin Nixon,‖ Learning PHP, MYSQL, JavaScript & CSS: A Step-by-step Guide to Creating Dynamic
Websites‖, O‘ Reilly Publications, 2nd Edition, 2018

201
Programs

1)Create a from with suitable information?


Ans:
<html>
<body background="c:\lucky\a3.jpg">
<p align=center><font color=red><font size=+1>biyani girls college</font></p>
<p align=center><font color=red><font size=+1>computer education center</font></p>
<p><font color=red><font size=+1>application form</font></p>
<form>
name <input type="text"width=30><br><br>
father's name <input type="text"width=30><br><br> date of birth <select name="dd"><br>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
<option>21</option>

202
<option>22</option>
<option>23</option>
<option>24</option>
<option>25</option>
<option>26</option>
<option>27</option>
<option>28</option>
<option>29</option>
<option>30</option>
<option>31</option>
</select>
<select name="mm">
<option>january</option>
<option>febuary</option>
<option>march</option>
<option>aprial</option>
<option>may</option>
<option>june</option>
<option>july</option>
<option>august</option>
<option>september</option>
<option>octomber</option>
<option>november</option>
<option>december</option>
</select>
<select name="yy">
<option>1980</option>
<option>1981</option>
<option>1982</option>
<option>1983</option>
<option>1984</option>
<option>1985</option>
<option>1986</option>

203
<option>1987</option>
<option>1988</option>
<option>1989</option>
<option>1990</option>
<option>1991</option>
<option>1992</option>
<option>1993</option>
<option>1994</option>
<option>1995</option>
<option>1996</option>
<option>1997</option>
<option>1998</option>
<option>1999</option>
<option>2000</option>
<option>2001</option>
<option>2002</option>
<option>2003</option>
<option>2004</option>
<option>2005</option>
<option>2006</option>
<option>2007</option>
<option>2008</option>
<option>2009</option>
<option>2010</option>
</select>
<br>
<br>
address <input type="text" width=50><br><br> sex<br><br>
male<input type="radio"name="a"value=0>

female<input type="radio"name="a"value=0>
<br>
<br> hobbies<br><br>

204
sports<input type="checkbox"name="s"value=0> shopping<input type="checkbox"name="sh"value=0>
<br>
computer<input type="checkbox"name="c"value=0> reading<input type="checkbox"name="r"value=0>
<br>
<br>
password<input type="password"><br><br>
<p align=center><input type="submit"name"yy"value="submit"></p>
<p align=center><input type="reset"name"b"value="reset"></p>
</form>
</html>

2) Create a different types of Bullets


Ans:
<html>
<title>Courses</title>
<body bgColor=orange> Courses are:-
<font size="+2">
<ol type=i>
<li><b><u>Graduation</u></b>
</font>
<ol type=i>
<li>BCA
<li>BSC

205
<li>BCOM
<li>BA
</ol>
<br>
<font size="+2">
<li><b><u>Post Graduation</u></b>
</font>
<font size="+2">
<ol type=i>
<li>MCA
<font size="+1">
<ol type=a>
<li>MCA-1
<li>MCA-111
<li>MCA-v
</font>
</ol>
<li>M.SC
</font>
</ol>
</body>
</html>
Output:

3) How to Displaying the Information Using JavaScript Code


Ans : ( a) document. write( )The document object is used to identify the webpage and it provides the
method or the function known as write( ) to display the information on the browser windows.

206
Note : JavaScript is case sensitive.
Consider the following code,
<html>
<head>
<title>Using the JavaScript </title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> document.write("Welcome to JavaScript");
</script>
</body>
</html>
Output :

4) How to Read the Information from the User:


Ans: 1) prompt( ) : This function is used to read the information from the user.
The general form is , prompt("message");
Consider the following code ,
<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var sname;
sname=prompt("Enter your name :"); document.write("<center><h1>Your Name is : "+sname+"

207
</h1></center>");
</script>
</body>
</html>

Output :

5) Write a JavaScript code to add two numbers.


Ans: First code display addition in string format:
<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var a,b,c;
a=prompt("Enter the value of a :"); b=prompt("Enter the value of b:"); c=a+b;
document.write("Sum= " + c);
</script>

208
</body>
</html>

Output :

6) Write a JavaScript code to check whether the number is even or odd. Ans
<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var num;
num=prompt("Enter the number :"); num=parseInt(num);

209
if(num%2==0)
document.write("number is even");

else
</script>
</body>
</html>
document.write("number is odd");

Output :

7) Write a JavaScript code to find the largest of three numbers. Ans:


<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var a,b,c;

210
a=prompt("Enter the value of a :");
b=prompt("Enter the value of b:"); c=prompt("Enter the value of c:");
a=parseInt(a); b=parseInt(b); c=parseInt(c);
if(a>b)
if(a>c)
document.write("a is largest");
else
document.write("c is largest");
if(b>c)
document.write("a is largest"); document.write("c is largest");
document.write("b is largest");
</script>
</body>
</html>

8) Write a program to display the format with n=4


1
12
123
1234

<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var i,j,n;
n=prompt("Enter the value of n:"); document.write("<br><br><br>") ; for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
document.write(j);
}

211
document.write("<br>");
}
</script>
</body>
</html>
Output :

9) Write a program to reverse the number.


<html>
<head>
<title>Using JavaScript</title>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var num,rev;

212
num=prompt("Enter the number :"); document.write("<br><br><br>") ; rev=0;
while(num!=0)
{
rev=rev*10+num%10; num=parseInt(num/10);

}
document.write("Reverse :"+rev);

</script>
</body>
</html>
output :

10) Write a program to find check the whether the number is Armstrong or not
<html>
<head>
<title>Using JavaScript</title>

213
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var num,sum,org;
num=prompt("Enter the number :");
num=parseInt(num); org=num;
document.write("<br><br><br>") ; sum=0;
do
{
sum=sum+(num%10)*(num%10)*(num%10); num=parseInt(num/10);

}while(num!=0); if(sum==org)
document.write("Armstrong Number .");
else
document.write("Not an armstrong number.");
</script>
</body>
</html>
output :

214
11) Write a program to find the factorial of given number
<html>
<head>
<title>Using JavaScript</title>
<script language="JavaScript"> function factorial(num)
{
var fact,i; fact=1;
for(i=1;i<=num;i++)
fact=fact*i; return fact;
}
</script>
</head>
<body bgcolor="#ccffee">
<script language="JavaScript"> var num,fact;
num=prompt("Enter the number:");
document.write("<br><br><br>") ; fact=factorial(num);
document.write("Factorial of " + num + " is = " + fact);
</script>
</body>
</html>

output :

215
12) Design the JavaScript code for creating the application which contains, three buttons,
Red, Green and Blue to change the background color accordingly.
Ans

<html>
<head>
<title>Using the Event Handling in JavaScript.</title>
<script language="JavaScript"> function changeRed( )
{
document.bgColor="red";
}
function changeGreen( )
{
document.bgColor="green";
}
function changeBlue( )
{
document.bgColor="blue";
}
</script>
</head>
<body bgcolor="#ccddee">

216
<center>
<br>
<br>
<form name="myform">
<input type="button" name="cmdred" onClick="changeRed( )" value="Red">
<input type="button" name="cmdgree" onClick="changeGreen( )" value="Green">
<input type="button" name="cmdblue" onClick="changeBlue( )" value="Blue">
</form>
</center>
</body>
</html>
output :

Design the application which contains three textboxes for two number and a result , and perform +,-
,*,/ and %.

13) Design the JavaScript code for creating the calculator application.
<html>
<head>
<title>Using Event Handling in JavaScript</title>
<script language="JavaScript"> function add( )
{
var a,b,c; a=document.myform.txta.value; b=document.myform.txtb.value; a=parseInt(a);

217
b=parseInt(b); c=a+b;
document.myform.txtc.value=c;
}
function subtract( )
{
var a,b,c; a=document.myform.txta.value; b=document.myform.txtb.value; a=parseInt(a);
b=parseInt(b); c=a-b;
document.myform.txtc.value=c;
}
function multiply( )

{
var a,b,c; a=document.myform.txta.value; b=document.myform.txtb.value; a=parseInt(a);
b=parseInt(b); c=a*b;
document.myform.txtc.value=c;
}
function divide( )
{
var a,b,c;

a=document.myform.txta.value; b=document.myform.txtb.value; a=parseInt(a);


b=parseInt(b); c=a/b;
document.myform.txtc.value=c;
}

function mod( )
{
var a,b,c; a=document.myform.txta.value; b=document.myform.txtb.value; a=parseInt(a);
b=parseInt(b); c=a%b;
document.myform.txtc.value=c;
}
</script>
</head>

218
<body bgcolor="#ccffee">
<center>
<br>
<br>
<form name="myform">
<b> Enter the value of a : </b><input type="text" name="txta"><br>
<b> Enter the value of b : </b><input type="text" name="txtb"><br>

<br>
<input type="button" name="cmdplus" value="+" onClick="add(
)"><input type="button" name="cmdminus" value="-" onClick="subtract(
)"><input type="button" name="cmdmult" value="*" onClick="multiply(
)"><input type="button" name="cmddiv" value="/" onClick="divide(
)"><input type="button" name="cmdmod" value="%" onClick="mod(
)"><br>
<br>
<b> Result : </b><input type="text" name="txtc">
<br>
</form>
</center>
</body>
</html>
<html>
<body>

219
14) Write a PHP program to display I to 5 numbers.

<?php
$i=1; while($i<=5)
{
echo "The number is " . $i . "<br />";
$i++;
}
?>

</body>
</html> Output:
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
15) Write a PHP program to find add two numbers
?php
if(isset($_POST['submit']))
{
$num1=$_POST['num1'];
$num2=$_POST['num2'];
$result=$num1+$num2;
echo "Sum of " .$num1. " and ".$num2. " is " .$result;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add two number</title>
</head>

220
<body>
<table>
<form name="add" method="post">
<tr>
<td>Number 1 :</td>
<td><input type="text" name="num1" required></td>
</tr>
<tr>
<td>Number 2 :</td>
<td><input type="text" name="num2" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Add" name="submit" /></td>
</tr>
</form>
</table>
</body>
</html>

16) Write a program to display a table.


?php
if(isset($_POST['submit']))
{
$num=$_POST['num'];
define('NUM',$num);
for($i=1 ; $i<=10 ; $i++)
{
echo $i*NUM;
echo '<br>';

221
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Table of a Number</title>
</head>
<body>
<table>
<form name="table" method="post">
<tr>
<td>Enter Number :</td>
<td><input type="text" name="num" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit" name="submit" /></td>
</tr>
</form>
</table>
</body>
</html>

222
17) Write a program to find the factorial of given number.
<?php
if(isset($_POST['submit']))
{
$num=$_POST['num'];
$fact = 1;
for ($i=$num; $i>=1; $i--)
{
$fact = $fact * $i;
}
echo "factorial of $num is $fact";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Factorial of a Number</title>
</head>
<body>
<table>
<form name="factorial" method="post">
<tr>
<td>Enter Number :</td>
<td><input type="text" name="num" required></td>
</tr>

223
<tr>
<td></td>
<td><input type="submit" value="Check" name="submit" /></td>
</tr>
</form>
</table>
</body>
</html>

18) write a PHP program to check the given number is Armstrong or not.
<?php
if(isset($_POST['submit']))
{
$num=$_POST['num'];
$sum=0;
$temp=$num;
while($temp!=0)
{
$rem=$temp%10;
$sum=$sum+$rem*$rem*$rem;
$temp=$temp/10;
}
if($num==$sum)
{
echo "$num is an Armstrong number";
}
else
{
echo "$num is not an Armstrong number";
}

224
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Armstrong Number</title>
</head>
<body>
<table>
<form name="armstrong" method="post">
<tr>
<td>Enter Number :</td>
<td><input type="text" name="num" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Check" name="submit" /></td>
</tr>
</form>
</table>
</body>
</html>

225
Model Question Paper

Model Question Paper


Reg. No.:

M.C.A. DEGREE EXAMINATION


Third Semester
DMC 6010 – WEB DESIGN
(Regulations)
Time: Three hours Maximum: 100 marks
Answer ALL questions.

PART A – (10 × 2 = 20 marks)


1. What are the differences between SMTP and POP?
2. What do you mean by WWW? How is it differing from internet?
3. What are the two different types of tags?
4. Write a short note on use of CSS.
5. What do you mean Positioning?
6. What is meant by opacity?
7. Mention The Various Java Script Object Models.
8. What technologies are being used in AJAX?
9. What is the difference between Print and Echo Statements?
10. What are the software components in LAMP?

PART B – (5 × 13 = 65 marks)
11. (a) What is SMTP? Explain the working of SMTP in detail. (13)
Or
(b) i) Write a brief note on File Transfer Protocol (6)
ii)Explain the compondents of WWW architecture witj a neat diagram. (7)

12.(a)Create a website using HTML for a ―Library management system‖. Your website should have a
home page which helps the user to navigate to various pages like student membership, books catlog,
transcations and serach pages. (13)
Or
(b) (i) Outline the different types of cascading style sheets. (7)

226
(ii) Compare the features of clide side scripting languages and server scripting languages. (6)
Or
13.(a) Explain the concepts of positioning in CSS. (13)
Or
b) (i) Discuss in Detail Layouts with Flexbox. (7)
(ii) Define Bootstrap.Explain the compondents of BootStrap. (6)

14. (a)(i) Explain the compondents of JSON srcture with necessary diagram. (6).
(ii) Explain the operators in JavScript with Examples. (7)

Or
b) i) Explain the storage concepts in detail (7)
ii) How to add and remove elements from JQuery? (6)

15) a) Explain the setting up the environment for LAMP server. (13)
(or)
b) i) Write a PHP code to read data from web pages. (6)
ii) Write a PHP code to display a table. (7)
PART C – (1 × 15 = 15 marks)

16(a) Create a PHP page and create a user form which gets five subjects marks out of 100 and then
displays the mark sheet of the students. Write a PHP Script to update the values in the database with
the new marks in subjects 5 as ―85‖.
(Or)
(b) Write a JavaScript code for validiating new user registration from which includes the fields like
username, passwords, confirm passwords, gender, date of birth, contact number and email-id.

227

You might also like