Dmc6010 Web Design
Dmc6010 Web Design
MASTER OF
COMPUTER APPLICATIONS
WEB DESIGN
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
Programs 202
4
UNIT-I
CONTENTS
Learning Objectives
Learning Outcomes
Overview
LEARNING OBJECTIVES
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.
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
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.
Request for
Web Page Request for
Network Web page
Web page
HTML file Web Page
HTML File
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,
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
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
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:
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.
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).
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.
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
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.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
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.
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
Source of IP address
Destination IP address
Option+padding
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
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.
TCP/IP
Storage Data transfer Process Data transfer Storage
process
Data connection
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.
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
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]>
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.
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.
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.
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.
6. font tag: -
This sets font size, color, and relative values for a particular text.
7. bold tag: -
This tag is used for implementing bold effect on the text
8. Italic tag: -
This implements italic effects on the text.
9. strong tag: -
This tag is used to always emphasized the text
10. tt tag: -
This tag is used to give typewriting effect on the text
<sub> .............</sub>
<sup> .............</sup>
<br>
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.
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
28
Example: -
<marquee align=‖ middle‖ behavior=‖ slide‖ bgcolr=‖ red‖ direction=‖ down‖>Raju</marquee>
……………
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).
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>
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>
Example:
<LI>item namen
</UL>
<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>
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>
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.
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>
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:
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.
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
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
preload auto Specifies if and how the author thinks the audio should be loaded when the page
metadata loads
none
<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
<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.
<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>
heading of
HTML <head>Contains elements describing the
<head> document Nothing will show
document</head>
44
maxlength="30">
<input type="Submit" value="Submit">
</form>
Example 2:
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:
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>
<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)
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
47
Capital Roman Numerals Capital Roman NumeralsSpecial Start
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:
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
<iframe src="URL"></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.
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>
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>
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
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>
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
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.
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. 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.
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.
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.
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
length Specifies a margin in px, pt, cm, etc. Default value is 0px
Inherit Specifies that the margin should be inherited from the parent element
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
Example:
p{
padding-top: 25px;
padding-right: 50px;
padding-bottom: 25px;
padding-left: 50px;
}
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)
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
64
This is a <span> element inside a paragraph.
Example
<span>Hello World</span>
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.
An article should make sense on its own, and it should be possible to distribute it independently from the
rest of the web site.
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>
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.
The <header> element represents a container for introductory content or a set of navigational links.
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
authorship information
copyright information
contact information
sitemap
back to top links
related documents
Example
A footer section in a document:
<footer>
<p>Author: Hege Refsnes</p>
<p><a href="mailto:[email protected]">[email protected]</a></p>
</footer>
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>
The <aside> element defines some content aside from the content it is placed in (like a sidebar).
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
<figure>
</figure>
Tag Description
69
<aside> Defines content aside from the page content
<details> Defines additional details that the user can view or hide
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.12 Bootstrap
Summary
Keywords
Self-Assessment QuestionsFurther
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.
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:
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.
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.
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.
<! 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:
In the above picture the boxes are not set the float property.
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.
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
<!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
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
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
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.
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.
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;
}
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.
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
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
}
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.
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
- 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.
container {
justify-content: flex-end.
88
Center: Center aligns all flex items to the center of the container.
Space-evenly: Space-evenly distributes space evenly around each item in the container.
.container {
Justify-content: space-evenly;
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:
<html>
<head>
<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>
<style>
*{
box-sizing: border-box.
. row::after {
content: "";
clear: both.
display: block.
[class*="col-"] {
float: left.
padding: 15px.
html {
.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.
.menu li:hover {
background-color: #0099cc;
.aside {
background-color: #33b5e5.
padding: 15px.
color: #ffffff.
text-align center.
font-size: 14px.
. footer {
background-color: #0099cc.
color: #ffffff.
text-align: center.
font-size: 12px.
padding: 15px.
/* For desktop: */
92
.col-1 {width: 8.33%;}
[class*="col-"] {
width: 100%.
</style>
</head>
<body>
<div class="header">
<h1>Chania</h1>
</div>
<div class="row">
<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="aside">
<h2>What? </h2>
<h2>Where? </h2>
<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
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.
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.
<html>
<head>
<style>
Div{
Border:3px solid.
Padding: 50px,50px.
Width: both;
Overflow: auto;
Font-size:34px.
Body {
Font-size:34px.
</style>
</head>
<body>
</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.
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 {
97
filter: progid:DXImageTransform.Microsoft.gradient(
startColorstr='#5efaff', endColorstr='#0316ed',
GradientType=1 );
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 {
opacity: 0.5;}
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.
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:
initial: Set the value as the default value for the property
assigned to 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:
<head>
<meta charset="utf-8">
<title>Flexbox demo</title>
<style>
.transform_animation {
width: 200px.
height: 100px.
margin-top:200px.
.transform_animation:hover {
</style>
</head>
<body>
<br>
<center>
</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.
property name: The name of the property that you want the
transition to take place.
101
Syntax:
transition-property: property_name.
<head>
<meta charset="utf-8">
<title>Flexbox demo</title>
<style>
.transform_animation {
width: 200px.
height: 100px.
margin-top:200px.
.transform_animation:hover {
transition-duration: 2s;
</style>
</head>
<body>
<br>
<center>
</div>
</center>
</body>
</html>
102
Fig:-3.14 Output of transform animation
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.
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.8 Ajax.
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.
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>
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
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-else.
112
}
</script>
<input type="button" onclick="msg()" value="call function"/>
Syntax
new Function ([arg1[, arg2[, argn]],] functionBody)
113
arg1, arg2, .... , argn - It represents the argument used by function.
functionBody - It represents the function definition
Method Description
apply () It is used to call a function contains this value and a single array of
arguments.
call () It is used to call a function contains this value and an argument list.
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)
114
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
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.
flatMap() It maps all array elements via mapping function, then flattens the result
into a new array.
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.
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.
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.
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.
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
118
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.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
<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.
120
JavaScript RegExp 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
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
Property Description
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.
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.
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
Boolean Properties
Property Description
In the following sections, we will have a few examples to illustrate the properties of Boolean object.
122
4.3.4 Boolean 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.
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
String Properties
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.
Method Description
Returns the index within the calling String object of the last occurrence of
lastIndexOf() the specified value, or -1 if not found.
search() Executes the search for a match between a regular expression and a
specified string.
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()
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
color="color"> tag.
125
Causes a string to be displayed as a superscript, as if it were in a <sup> tag
sup()
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
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 will use ordinal numbers to access and to set values inside an array as follows.
Here is a list of the properties of the Array object along with their description.
Property Description
input This property is only present in arrays created by regular expression matches.
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.
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.
map() Creates a new array with the results of calling a provided function on every
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.
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.
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.
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()
Returns the "date" portion of the Date as a string, using the current
toLocaleDateString() locale's conventions.
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();
// 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>";
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
Math Properties
Property Description
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
Returns EN, where N is the argument, and E is Euler's constant, the base of the
exp()
natural logarithm.
pow() Returns base to the exponent power, that is, base exponent.
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.
134
4.3.2 Data Types in JSON
Table 4.18 Data types in JSON
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
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.
Type Description
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.
Type Description
F From feed
Syntax
var json-object-name = {string : "string value",…..}
Example:
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
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.
mouseover on mouseover When the cursor of the mouse comes over the
element
140
mousedown onmousedown When the mouse button is pressed over the
element
Keydown & Keyup onkeydown When the user press and then release the key
&onkeyup
4.5.3 Form events:
Table 4.24 Form Events
141
4.5.4 Window/Document events
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
142
<script language="Javascript" type="text/Javascript"> function
mouseoverevent()
{
alert("This is JavaTpoint");
}
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
143
document.getElementById("input1");
alert("Pressed a key");
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 :
<input type="text" id="uname" onBlur="check()"></h3>
</td>
<td>
<p id="xyz"></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Password &n
bsp; :
<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">
&nbs
p; &n
146
bsp; Email
Address :
<input type="text" name="mail" onBlur="email()"> @
<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> .
<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
:
<input type="text" name="ad" onBlur="addr()"></h3>
</td>
<td>
<p id="p2"></p>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Line1 &n
bsp; :
<input type="text" name="l1"></h3>
</td>
</tr>
<tr>
<td>
<h3 align="center">
Line2 &n
bsp; :
<input type="text" name="l2"></h3>
</td>
</tr>
147
<tr>
<td>
<h3 align="center">
Pin
:
<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
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
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>
</head>
<body>
<h1>JavaScript sample</h1>
<div id="square"></div>
</body>
</html>
Make a new CSS file, style5.css. Copy and paste the content
from here:
#square {
width: 20em;
height: 20em;
margin-bottom: 1em;
button {
149
}
Make a new text file, script5.js. Copy and paste the content
from here:
// JavaScript demonstration
function doDemo () {
square.style.backgroundColor = "#fa4";
button.setAttribute("disabled", "true");
square.style.backgroundColor = "transparent";
button.removeAttribute("disabled");
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.
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.
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.
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) {
3 }
4 else {
6 }
1 if (Modernizr.sessionstorage) {
151
3 }
4 else {
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)
• 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)
152
Typical AJAX Event
• A typical AJAX transaction looks like this:
• 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
• 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:
153
4.8.4 An AJAX Architecture
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.
(!xmlHttp)
154
{ return false; }
xmlHttp.onreadystatechange = function()
if (xmlHttp.readyState == 4)
{ alert("Request complete");
xmlHttp.send(null);
• Every time the readyState property changes the onreadystatechange property (a function) is called
xmlHttp.onreadystatechange = function()
{ if (xmlHttp.readyState == 4)
{ alert("Request complete"); }
var requestURI =
155
"http://myserver.org/somepage.txt";
xmlHttp.send(null);
– The domain of the uri argument must be the same as the domain of the current page
– xmlHttp.send(content);
var xmlHttp =
GetXmlHttpObject(); if
xmlHttp.onreadystatechange = function()
{ if (xmlHttp.readyState == 4) { alert("Request
"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.
xmlHttp.onreadystatechange = function()
{ if (xmlHttp.readyState == 4)
{ textNode.nodeValue = xmlHttp.responseText; } }
true);
xmlHttp.send(null);
greatbeyond.org#!/usr/bin/perl
print("Content-type:
text/plain\n\n"); print("57
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.onreadystatechange = function() { if
(xmlHttp.readyState == 4) {
}}
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 jQuery element selector selects elements based on the element name.
$("p")
Example
Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
158
});
});
We will look at four jQuery methods that are used to add new content:
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(){
});
$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<ol>
</ol>
</body>
160
</html>
Remove Elements/Content
To remove elements and content, there are mainly two jQuery methods:
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>
<br>
</body>
</html>
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.
This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to
do the job −
Syntax
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
<html>
<head>
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>
STAGE
</div>
</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.
164
4.12 Animation with Jquery
jQuery Animations - The animate() Method
Syntax:
$(selector).animate({params},speed,callback);
The optional speed parameter specifies the duration of the effect. It can take the following values: "slow", "fast", or
milliseconds.
<!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>
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.7 Cookies
LEARNING OBJECTIVES
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.
<html>
<head>
<title>Hello World</title>
<body>
<?php echo "Hello, World!";?>
</body>
</html>
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.
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.
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:
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
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;
}
?>
Example:
<?php
for ($i = 0; $i < 10; $i++){
$product = 10 * $i;
echo "The product of 10 * $i is $product <br/>";
}
?>
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
<?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
175
Create an Array in PHP:
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
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 />";
}
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);
</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
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 ));
</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.
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
If fopen is unable to open the file, it returns 0. This can be used to exit the function with an
appropriate message.
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.
The fclose function is used to close a file when you are finished with it.fclose($fp);
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.
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);
?>
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‖;
?>
if(is_dir($filename))
echo $filename . ― is a directory‖;
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‘;
}
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.
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>
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>
<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>
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.
Now we are going to discuss the steps for WAMP Server Installation.
Step 1:
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.
Now your file is downloaded and save that *.exe file in your system drive location.
187
After the file has downloaded the following tray icon file is visible and stored at your system location
Figure 5.4
Step 2:
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.
Now the orange color try Icon placed at the start menu is visible.
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
189
Figure 5.8
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.
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
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.
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.
191
Step 3:
After installation is completed host a simple PHP website via WAMPSERVER. The following steps to be
noted.
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:
Now refresh our localhost in browser and we find our sample website appears under projects title.
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.
Set the username as root and make empty password column and hit go. The admin page window will
open like the following,
193
After the page opens in your right side window, click database and choose to create database.
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.
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.
Now your website is ready to connect the database and now browse your site in localhost:81
195
Figure5. 22: Login page
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.
<?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
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>
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:
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 :
207
</h1></center>");
</script>
</body>
</html>
Output :
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 :
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>
<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 :
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;
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>
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
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