Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 189

L T P C

UAD1601 WEB TECHNOLOGY


3 0 0 3
OBJECTIVES:

 To understand themarkup languagewith style sheets.


 To design interactive web pages using Scripting languages and front end frameworks.
 To learn server side programming using servlets and JSP.
 To develop web pages using PHP and XML.
 To understand AJAX and web services

UNIT I WEBSITE BASICS, HTML 5 AND CSS 3 9

Web Essentials: Clients, Servers and Communication – The Internet – Basic Internet protocols – World
wide web – HTTP Request Message – HTTP Response Message – Web Clients – Web Servers –
HTML5 – Tables – Lists – Image – HTML5 control elements – Semantic elements – Drag and Drop –
Audio – Video controls - CSS3 – Inline, embedded and external style sheets –Backgrounds – Border
Images – Colors – Shadows – Text – Transformations – Transitions – Animations.

UNITII CLIENT SIDE SCRIPTINGWITHFRAMEWORK 9


Java Script: An introduction to JavaScript–JavaScript DOM Model-Validation-Built-in objects-Event
HandlingDHTML with JavaScript– AngularJS:Introduction to AngularJS –Directives –Filters - Directives
in DOM - Events – Expression – Controller & Scope – Module & API.

UNIT III SERVER SIDE SCRIPTING 9


Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actionsSession Handling-
Understanding Cookies- Installing and Configuring Apache Tomcat Web Server- DATABASE
CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-
Creating HTML forms by embedding JSP code.

UNIT IV PHP and XML 9


An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions- Form Validation
- XML: Basic XML- Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers
and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).

UNIT V AJAX AND WEB SERVICES 9


AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods; Web Services:
Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a Web services
(WSDL)-Consuming a web service, Database Driven web service from an application –SOAP.

TOTAL:45 PERIODS
TEXT BOOK :
1. Deitel and Deitel and Nieto, “Internet and World Wide Web - How to Program”, Prentice Hall, 5th
Edition, 2011.
2. John Dean,”Web programming with HTML5, CSS” Jones and Bartlett learning, US, 2018.
3. AngularJS in 8 hours for beginners, Learn coding fast (2nd Edition) by Ray Yao
REFERENCES :
1. Stephen Wynkoop and John Burke “Running a Perfect Website”, QUE, 2nd Edition,1999.
2. Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley Publications, 2009.
3. Jeffrey C and Jackson, “Web Technologies A Computer Science Perspective”, Pearson Education,
2011.
4. Gopalan N.P. and Akilandeswari J., “Web Technology”, Prentice Hall of India, 2011.
5. UttamK.Roy, “Web Technologies”, Oxford University Press, 2011.

COURSE OUTCOMES:
At the end of the course, the student should be able to:
1. Design simple web pages using HTML5 and CSS3.
2. Create dynamic web pages using java script and AngularJS
3. Program server side web pages using JSPwith data base connectivity
4. Represent web data using XML and develop web pages using PHP.
5. Understand various web services and how these web services interact.

UNIT I - WEBSITE BASICS, HTML 5 AND CSS 3

Web Essentials: Clients, Servers and Communication – The Internet – Basic Internet protocols – World wide
web – HTTP Request Message – HTTP Response Message – Web Clients – Web Servers – HTML5 – Tables
– Lists – Image – HTML5 control elements – Semantic elements – Drag and Drop – Audio – Video controls -
CSS3 – Inline, embedded and external style sheets –Backgrounds – Border Images – Colors – Shadows – Text
– Transformations – Transitions – Animations.

WEB ESSENTIALS: CLIENTS, SERVERS AND COMMUNICATION


Client

A client can be a device or a machine.

A client program runs on the local machine, requesting service from the server. A client program is a finite program
means that the service is started by the user and terminates when the service is completed. For instance, web
browser.

A client device is a machine that the end-user uses to access the web. Examples of clients are smartphones,
desktops, laptops, etc.
It is simple and less powerful and used for simple tasks. It has a basic hardware configuration. Clients are
categorized into thin client, fat client, and hybrid client. Thin client is lightweight and relies on the resources of the
host computer. A fat client (or thick client) lightly relies on the server and provides rich functionality. A hybrid
client is the combination of the characteristics of a thin client and a thick client.

Server

A server is like a computer program, which is used to provide functionality to other programs. It can be any
computerized process called by a client to distribute the work and share the resources.

It receives and responds to requests made over a network. Server receives the request from the client for a web
document, and it sends the requested information to the client's computer.

A device can be both a client and a server at the same time, as an individual system has the ability to provide
resources and use them from another system in one go. In a single machine, there can be multiple servers.

Server has high efficiency and performance. Simultaneous multiple-user login and request processing are
supported in servers. Some of the complex tasks like fulfilling client requests, storing and processing large
datasets, data analysis are common for servers.

There can be various types of servers: web server, application server, database server, cloud server, file server,
proxy server, mail server, and many more.

The basic difference between the client and server is that client relies on the services of the server, whereas the
server authorizes the client's requests and facilitates them with the requested services. Servers can store and
analyze the large data sets, whereas clients are not suited for such tasks.
Most of the servers are never turned off; they are always on. Switching off servers may be disastrous for client
systems that continuously request the services. Whereas the client systems can be switch off without any fear.

Client v/s Server

Now, let's see the comparison chart between client and server. We are comparing both terms based on some
characteristics.

Based on Client Server

Basic Client relies on the services of server, Server authorizes the client's requests
functionality and generates requests for various and facilitates them with the requested
services. services.

Configuration The configuration of client systems is The configuration of the server is more
simple. Their tasks are limited to complex and sophisticated. Server has
generating requests. It has a basic advanced hardware configuration.
hardware configuration.

Efficiency The efficiency of client is limited. The performance of server is high, and
they are highly efficient.

Tasks The common tasks for client are simple The complex tasks like fulfilling client
and mostly include requesting services. requests, storing and processing large
datasets, data analysis are common for
server.

Switch off The client systems can be switch off Switching off servers may be disastrous
without any fear. for client systems that continuously
request the services.

Login Support There can be single user logins. Server support multiple user login and
request processing simultaneously.

Examples Examples of clients are smartphones, Examples of servers are web servers,
desktops, laptops, etc. file servers, database servers, etc.

THE INTERNET
What is the Internet?

Network of networks – connect the computers through over the world.

The Internet is a worldwide telecommunications system that provides connectivity for millions of other, smaller
networks; therefore, the Internet is often referred to as a network of networks. It allows computer users to
communicate with each other across distance and computer platforms.

The Internet began in 1969 as the U.S. Department of Defense's Advanced Research Project Agency (ARPA) to
provide immediate communication within the Department in case of war. Computers were then installed at U.S.
universities with defense related projects. As scholars began to go online, this network changed from military use to
scientific use. As ARPAnet grew, administration of the system became distributed to a number of organizations,
including the National Science Foundation (NSF). This shift of responsibility began the transformation of the
science oriented ARPAnet into the commercially minded and funded Internet used by millions today.

The Internet acts as a pipeline to transport electronic messages from one network to another network. At the heart
of most networks is a server, a fast computer with large amounts of memory and storage space. The server
controls the communication of information between the devices attached to a network, such as computers, printers,
or other servers.

An Internet Service Provider (ISP) allows the user access to the Internet through their server. Many teachers use a
connection through a local university as their ISP because it is free. Other ISPs, such as America Online, telephone
companies, or cable companies provide Internet access for their members.

You can connect to the Internet through telephone lines, cable modems, cellphones and other mobile devices.

Why do I need a browser?

Once you have an account with an Internet service provider, you can access the Web through a browser, such as
Safari or Microsoft Internet Explorer. The browser is the application responsible for allowing a user's computer to
read and display web documents.

Hypertext Markup Language (HTML) is the language used to write web pages. A browser takes the HTML and
translates it into the content you see on the screen. You will note your cursor turns into a pointing finger over some
images or text on the page. This indicates a link to additional information and it can be either a link to additional
web pages, email, newsgroups, audio, video, or any number of other exciting files.

BASIC INTERNET PROTOCOLS


Transmission Control Protocol (TCP)

TCP is a connection oriented protocol and offers end-to-end packet delivery. It acts as back bone for connection.It
exhibits the following key features:
Transmission Control Protocol (TCP) corresponds to the Transport Layer of OSI Model.
TCP is a reliable and connection oriented protocol.
TCP offers:
o Stream Data Transfer.
o Reliability.
o Efficient Flow Control
o Full-duplex operation.
o Multiplexing.
 TCP offers connection oriented end-to-end packet delivery.
 TCP ensures reliability by sequencing bytes with a forwarding acknowledgement number that
indicates to the destination the next byte the source expect to receive.
 It retransmits the bytes not acknowledged with in specified time period.
TCP Services
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
 Reliable Service
Stream Deliver Service
TCP protocol is stream oriented because it allows the sending process to send data as stream of bytes and the
receiving process to obtain data as stream of bytes.
Sending and Receiving Buffers
It may not be possible for sending and receiving process to produce and obtain data at same speed, therefore,
TCP needs buffers for storage at sending and receiving ends.
Bytes and Segments
The Transmission Control Protocol (TCP), at transport layer groups the bytes into a packet. This packet is called
segment. Before transmission of these packets, these segments are encapsulated into an IP datagram.
Full Duplex Service
Transmitting the data in duplex mode means flow of data in both the directions at the same time.
Connection Oriented Service
TCP offers connection oriented service in the following manner:
1. TCP of process-1 informs TCP of process – 2 and gets its approval.
2. TCP of process – 1 and TCP of process – 2 and exchange data in both the two directions.
3. After completing the data exchange, when buffers on both sides are empty, the two TCP’s destroy their
buffers.
Reliable Service
For sake of reliability, TCP uses acknowledgement mechanism.

Internet Protocol (IP)

Internet Protocol is connectionless and unreliable protocol. It ensures no guarantee of successfully transmission


of data.
In order to make it reliable, it must be paired with reliable protocol such as TCP at the transport layer.
Internet protocol transmits the data in form of a datagram as shown in the following diagram:

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.
User Datagram Protocol (UDP)

Like IP, UDP is connectionless and unreliable protocol. It doesn’t require making a connection with the host to
exchange data. Since UDP is unreliable protocol, there is no mechanism for ensuring that data sent is received.
UDP transmits the data in form of a datagram. The UDP datagram consists of five parts as shown in the following
diagram:

Points to remember:
 UDP is used by the application that typically transmit small amount of data at one time.
 UDP provides protocol port used i.e. UDP message contains both source and destination port
number, that makes it possible for UDP software at the destination to deliver the message to correct
application program.

File Transfer Protocol (FTP)

FTP is used to copy files from one host to another. FTP offers the mechanism for the same in following manner:
 FTP creates two processes such as Control Process and Data Transfer Process at both ends i.e. at
client as well as at server.
 FTP establishes two different connections: one is for data transfer and other is for control information.
 Control connection is made between control processes while Data Connection is made
between<="" b="" style="box-sizing: border-box;">
 FTP uses port 21 for the control connection and Port 20 for the data connection.
Trivial File Transfer Protocol (TFTP)

Trivial File Transfer Protocol is also used to transfer the files but it transfers the files without authentication.
Unlike FTP, TFTP does not separate control and data information. Since there is no authentication exists, TFTP
lacks in security features therefore it is not recommended to use TFTP.
Key points
 TFTP makes use of UDP for data transport. Each TFTP message is carried in separate UDP
datagram.
 The first two bytes of a TFTP message specify the type of message.
 The TFTP session is initiated when a TFTP client sends a request to upload or download a file.
 The request is sent from an ephemeral UDP port to the UDP port 69 of an TFTP server.

Difference between FTP and TFTP

S.N. Parameter FTP TFTP

1 Operation Transferring Files Transferring Files

2 Authentication Yes No
3 Protocol TCP UDP

4 Ports 21 – Control, 20 – Data Port 3214, 69, 4012

5 Control and Data Separated Separated

6 Data Transfer Reliable Unreliable

Telnet

Telnet is a protocol used to log in to remote computer on the internet. There are a number of Telnet clients having
user friendly user interface. The following diagram shows a person is logged in to computer A, and from there, he
remote logged into computer B.

Hyper Text Transfer Protocol (HTTP)

HTTP is a communication protocol. It defines mechanism for communication between browser and the web server.
It is also called request and response protocol because the communication between browser and server takes
place in request and response pairs.
HTTP Request
HTTP request comprises of lines which contains:
 Request line
 Header Fields
 Message body
Key Points
 The first line i.e. the Request line specifies the request method i.e. Get or Post.
The second line specifies the header which indicates the domain name of the server from where
index.htm is retrieved.
HTTP Response
Like HTTP request, HTTP response also has certain structure. HTTP response contains:
 Status line
 Headers
 Message body

Internet Protocols are a set of rules that governs the communication and exchange of data over the internet. Both
the sender and receiver should follow the same protocols in order to communicate the data. In order to
understand it better, let’s take an example of a language. Any language has its own set of vocabulary and
grammar which we need to know if we want to communicate in that language. Similarly, over the internet
whenever we access a website or exchange some data with another device then these processes are governed
by a set of rules called the internet protocols.
Working of internet protocol: The internet and many other data networks work by organizing data into small
pieces called packets. Each large data sent between two network devices is divided into smaller packets by the
underlying hardware and software. Each network protocol defines the rules for how its data packets must be
organized in specific ways according to the protocols the network supports.  
Why do we need protocols?
It may be that the sender and receiver of data are parts of different networks, located in different parts of the
world having different data transfer rates. So, we need protocols to manage the flow control of data, access
control of the link being shared in the communication channel. Suppose there is a sender X who has a data
transmission rate of 10 Mbps. And, there is a receiver Y who has a data receiving rate of 5Mbps. Since the rate
of receiving the data is slow so some data will be lost during transmission. In order to avoid this, the receiver Y
needs to inform sender X about the speed mismatch so that the sender X can adjust its transmission rate.
Similarly, the access control decides the node which will access the link shared in the communication channel at
a particular instant of time. If not the transmitted data will collide if many computers send data simultaneously
through the same link resulting in the corruption or loss of data.
Types of internet protocol
The Internet Protocols are of different types having different uses:-
1. TCP/IP(Transmission Control Protocol/ Internet Protocol): These are a set of standard rules that allows
different types of computers to communicate with each other. The IP protocol ensures that each computer that is
connected to the Internet is having a specific serial number called the IP address. TCP specifies how data is
exchanged over the internet and how it should be broken into IP packets. It also makes sure that the packets
have information about the source of the message data, the destination of the message data, the sequence in
which the message data should be re-assembled, and checks if the message has been sent correctly to the
specific destination. The TCP is also known as a connection-oriented protocol.
The functionality of TCP/IP is divided into 4 layers with each one having specific protocols:
1. Application Layer: The application layer makes sure that the data from the sending end is received in
a format that is acceptable and supported at the receiving end.
2. Transport Layer: The transport layer is responsible for the smooth transmission of data from one end
to the other. It is also responsible for reliable connectivity, error recovery, and flow control of the data.
3. Internet Layer: This Internet Layer moves packets from source to destination by connecting
independent networks.
4. Network Access Layer: The Network Access Layer sees how a computer connects to a network.

2. SMTP(Simple Mail Transfer Protocol): These protocols are important for sending and distributing outgoing
emails. This protocol uses the header of the mail to get the email id of the receiver and enters the mail into the
queue of outgoing mails. And as soon as, it delivers the mail to the receiving email id, it removes the email from
the outgoing list. The message or the electronic mail may consider of text, video, image etc. It helps in setting up
of some communication server rules.
3. PPP(Point to Point Protocol): It is a communication protocol that is used to create a direct connection
between two communicating devices. This protocol defines the rules using which two devices will authenticate
with each other and exchange information with each other. For example, A user connects his PC to the server of
an Internet Service Provider also uses PPP. Similarly, for connecting two routers for direct communication it uses
PPP.
4. FTP (File Transfer Protocol): This protocol is used for transferring files from one system to the other. This
works on a client-server model. When a machine requests for file transfer from another machine, the FTO sets
up a connection between the two and authenticates each other using their ID and Password. And, the desired file
transfer takes place between the machines.
5. SFTP(Secure File Transfer Protocol): SFTP which is also known as SSH FTP refers to File Transfer
Protocol (FTP) over Secure Shell (SSH) as it encrypts both commands and data while in transmission. SFTP acts
as an extension to SSH and encrypts files and data then sends them over a secure shell data stream. This
protocol is used to remotely connect to other systems while executing commands from the command line.
6. HTTP(Hyper Text Transfer Protocol): This protocol is used to transfer hypertexts over the internet and it is
defined by the www(world wide web) for information transfer. This protocol defines how the information needs to
be formatted and transmitted. And, it also defines the various actions the web browsers should take in response
to the calls made to access a  particular web page. Whenever a user opens their web browser, the user will
indirectly use HTTP as this is the protocol that is being used to share text, images, and other multimedia files on
the World Wide Web. 
Note: Hypertext refers to the special format of the text that can contain links to other texts.     
7. HTTPS(HyperText Transfer Protocol Secure): HTTPS is an extension of the Hypertext Transfer Protocol
(HTTP). It is used for secure communication over a computer network with the SSL/TLS protocol for encryption
and authentication. So, generally, a  website has an HTTP protocol but if the website is such that it receives
some sensitive information such as credit card details, debit card details, OTP, etc then it requires an SSL
certificate installed to make the website more secure. So, before entering any sensitive information on a website,
we should check if the link is HTTPS or not. If it is not HTTPS then it may not be secure enough to enter sensitive
information.
8. TELNET(Terminal Network): TELNET is a standard TCP/IP protocol used for virtual terminal service given by
ISO. This enables one local machine to connect with another. The computer which is being connected is called a
remote computer and which is connecting is called the local computer. TELNET operation lets us display
anything being performed on the remote computer in the local computer. This operates on the client/server
principle. The local computer uses the telnet client program whereas the remote computer uses the telnet server
program.
9. POP3(Post Office Protocol 3): POP3 stands for Post Office Protocol version 3. It has two Message Access
Agents (MAAs) where one is client MAA (Message Access Agent) and another is server MAA(Message Access
Agent) for accessing the messages from the mailbox. This protocol helps us to retrieve and manage emails from
the mailbox on the receiver mail server to the receiver’s computer. This is implied between the receiver and
receiver mail server. It can also be called as one way client server protocol. The POP3 WORKS ON THE 2
PORTS I.E. PORT 110 AND PORT 995.
10. IPv4: The fourth and initially widely used version of the Internet Protocol is called IPv4 (Internet Protocol
version 4). It is the most popular version of the Internet Protocol and is in charge of distributing data packets
throughout the network. Maximum unique addresses for IPv4 are 4,294,967,296 (232), which are possible due to
the use of 32-bit addresses. The network address and the host address are the two components of each
address. The host address identifies a particular device within the network, whereas the network address
identifies the network to which the host belongs.In “dotted decimal” notation, which is the standard for IPv4
addresses, each octet (8 bits) of the address is represented by its decimal value and separated by a dot (e.g.
192.168.1.1).
11. IPv6: The most recent version of the Internet Protocol, IPv6, was created to address the IPv4 protocol’s
drawbacks. A maximum of 4.3 billion unique addresses are possible with IPv4’s 32-bit addresses. Contrarily,
IPv6 uses 128-bit addresses, which enable a significantly greater number of unique addresses. This is significant
because IPv4 addresses were running out and there are an increasing number of devices that require internet
access. Additionally, IPv6 offers enhanced security features like integrated authentication and encryption as well
as better support for mobile devices. IPv6 support has spread among websites and internet service providers,
and it is anticipated to gradually displace IPv4 as the main internet protocol.
12. ICMP: ICMP (Internet Control Message Protocol) is a network protocol that is used to send error messages
and operational information about network conditions. It is an integral part of the Internet Protocol (IP) suite, and
is used to help diagnose and troubleshoot issues with network connectivity. ICMP messages are typically
generated by network devices, such as routers, in response to errors or exceptional conditions encountered in
forwarding a datagram. Some examples of ICMP messages include:
 Echo Request and Echo Reply (ping)
 Destination Unreachable
 Time Exceeded
 Redirect
ICMP can also be used by network management tools to test the reachability of a host and measure the round-
trip time for packets to travel from the source to destination and back. It should be noted that ICMP is not a
secure protocol, it can be used in some types of network attacks like DDoS amplification.
13. UDP: UDP (User Datagram Protocol) is a connectionless, unreliable transport layer protocol. Unlike TCP, it
does not establish a reliable connection between devices before transmitting data, and it does not guarantee that
data packets will be received in the order they were sent or that they will be received at all. Instead, UDP simply
sends packets of data to a destination without any error checking or flow control. UDP is typically used for real-
time applications such as streaming video and audio, online gaming, and VoIP (Voice over Internet Protocol)
where a small amount of lost data is acceptable and low latency is important. UDP is faster than TCP because it
has less overhead. It doesn’t need to establish a connection, so it can send data packets immediately. It also
doesn’t need to wait for confirmation that the data was received before sending more, so it can transmit data at a
higher rate.
14. IMAP: IMAP (Internet Message Access Protocol) is a protocol used for retrieving emails from a mail server. It
allows users to access and manage their emails on the server, rather than downloading them to a local device.
This means that the user can access their emails from multiple devices and the emails will be synced across all
devices. IMAP is more flexible than POP3 (Post Office Protocol version 3) as it allows users to access and
organize their emails on the server, and also allows multiple users to access the same mailbox.
15. SSH: SSH (Secure Shell) is a protocol used for secure remote login and other secure network services. It
provides a secure and encrypted way to remotely access and manage servers, network devices, and other
computer systems. SSH uses public-key cryptography to authenticate the user and encrypt the data being
transmitted, making it much more secure than traditional remote login protocols such as Telnet. SSH also allows
for secure file transfers using the SCP (Secure Copy) and SFTP (Secure File Transfer Protocol) protocols. It is
widely used in Unix-based operating systems and is also available for Windows. It is commonly used by system
administrators, developers, and other technical users to remotely access and manage servers and other network
devices.

WORLD WIDE WEB


What makes up the World Wide Web?

The Internet is often confused with the World Wide Web. The misperception is that these two terms are
synonymous. The Internet is the collection of the many different systems and protocols. The World Wide Web,
developed in 1989, is actually one of those different protocols. As the name implies, it allows resources to be linked
with great ease in an almost seamless fashion.

The World Wide Web contains a vast collection of linked multimedia pages that is ever-changing. However, there
are several basic components of the Web that allow users to communicate with each other. Below you will find
selected components and their descriptions.

TCP/IP protocols
In order for a computer to communicate on the Internet, a set of rules or protocols computers must follow to
exchange messages was developed. The two most important protocols allowing computers to transmit data on the
Internet are Transmission Control Protocol (TCP) and Internet Protocol (IP). With these protocols, virtually all
computers can communicate with each other. For instance, if a user is running Windows on a PC, he or she can
communicate with iPhones.

Domain name system


An Internet address has four fields with numbers that are separated by periods or dots. This type of address is
known as an IP address. Rather than have the user remember long strings of numbers, the Domain Name System
(DNS) was developed to translate the numerical addresses into words. For example, the address fcit.usf.edu is
really 131.247.120.10.

URLs
Addresses for web sites are called URLs (Uniform Resource Locators). Most of them begin with http (HyperText
Transfer Protocol), followed by a colon and two slashes. For example, the URL for the Florida Center for
Instructional Technology is https://fcit.usf.edu/ .

Some of the URL addresses include a directory path and a file name. Consequently, the addresses can become
quite long. For example, the URL of a web page may be:
https://fcit.usf.edu/holocaust/default.htm. In this example, "default.htm" is the name of the file which is in a directory
named "holocaust" on the FCIT server at the University of South Florida.

Top-level domain
Each part of a domain name contains certain information. The first field is the host name, identifying a single
computer or organization. The last field is the top-level domain, describing the type of organization and occasionally
country of origin associated with the address.

Top-level domain names include:

.com Commercial
.edu Educational

.gov US Government

.int Organization

.mil US Military

.net Networking Providers

.org Non-profit Organization

Domain name country codes include, but are not limited to:

.au Australia

.de Germany

.fr France

.nl Netherlands

.uk United Kingdom

.us United States

Paying attention to the top level domain may give you a clue as to the accuracy of the information you find. For
example, information on a "com" site can prove useful, but one should always be aware that the intent of the site
may be to sell a particular product or service. Likewise, the quality of information you find on the "edu" domain may
vary. Although many pages in that domain were created by the educational institutions themselves, some "edu"
pages may be the private opinions of faculty and students. A common convention at many institutions is to indicate
a faculty or student page with a ~ (tilde) in the address. For instance, https://fcit.usf.edu/~kemker/default.htm is a
student's personal web page.

HTTP REQUEST MESSAGE – HTTP RESPONSE MESSAGE


HTTP - Messages
HTTP is based on the client-server architecture model and a stateless request/response protocol that operates by
exchanging messages across a reliable TCP/IP connection.
An HTTP "client" is a program (Web browser or any other client) that establishes a connection to a server for the
purpose of sending one or more HTTP request messages. An HTTP "server" is a program ( generally a web server
like Apache Web Server or Internet Information Services IIS, etc. ) that accepts connections in order to serve HTTP
requests by sending HTTP response messages.
HTTP makes use of the Uniform Resource Identifier (URI) to identify a given resource and to establish a
connection. Once the connection is established, HTTP messages are passed in a format similar to that used by
the Internet mail [RFC5322] and the Multipurpose Internet Mail Extensions (MIME) [RFC2045]. These messages
include requests from client to server and responses from server to client which will have the following format:
HTTP-message = <Request> | <Response> ; HTTP/1.1 messages
HTTP requests and HTTP responses use a generic message format of RFC 822 for transferring the required data.
This generic message format consists of the following four items.

 A Start-line

 Zero or more header fields followed by CRLF

 An empty line (i.e., a line with nothing preceding the CRLF)


 indicating the end of the header fields

 Optionally a message-body

In the following sections, we will explain each of the entities used in an HTTP message.

Message Start-Line

A start-line will have the following generic syntax:


start-line = Request-Line | Status-Line
We will discuss Request-Line and Status-Line while discussing HTTP Request and HTTP Response messages
respectively. For now, let's see the examples of start line in case of request and response:
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)


Header Fields

HTTP header fields provide required information about the request or response, or about the object sent in the
message body. There are four types of HTTP message headers:
 General-header: These header fields have general applicability for both request and response
messages.
 Request-header: These header fields have applicability only for request messages.
 Response-header: These header fields have applicability only for response messages.
 Entity-header: These header fields define meta information about the entity-body or, if no body is
present, about the resource identified by the request.
All the above mentioned headers follow the same generic format and each of the header field consists of a name
followed by a colon (:) and the field value as follows:
message-header = field-name ":" [ field-value ]
Following are the examples of various header fields:
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

Message Body

The message body part is optional for an HTTP message but if it is available, then it is used to carry the entity-body
associated with the request or response. If entity body is associated, then usually Content-Type and Content-
Length headers lines specify the nature of the body associated.
A message body is the one which carries the actual HTTP request data (including form data and uploaded, etc.)
and HTTP response data from the server ( including files, images, etc.). Shown below is the simple content of a
message body:
<html>
<body>

<h1>Hello, World!</h1>

</body>
</html>
Next two chapters will make use of above explained concepts to prepare HTTP Requests and HTTP Responses.
HTTP - Requests
An HTTP client sends an HTTP request to a server in the form of a request message which includes following
format:

 A Request-line

 Zero or more header (General|Request|Entity) fields followed by CRLF

 An empty line (i.e., a line with nothing preceding the CRLF)


 indicating the end of the header fields

 Optionally a message-body

The following sections explain each of the entities used in an HTTP request message.

Request-Line

The Request-Line begins with a method token, followed by the Request-URI and the protocol version, and ending
with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF
Let's discuss each of the parts mentioned in the Request-Line.

Request Method

The request method indicates the method to be performed on the resource identified by the given  Request-URI.
The method is case-sensitive and should always be mentioned in uppercase. The following table lists all the
supported methods in HTTP/1.1.

S.N Method and Description


.

1 GET
The GET method is used to retrieve information from the given server using a
given URI. Requests using GET should only retrieve data and should have no
other effect on the data.
2 The absoluteURI is used when an HTTP request is being made to a proxy. The
proxy is requested to forward the request or service from a valid cache, and
return the response. For example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1

3 The most common form of Request-URI is that used to identify a resource on an


origin server or gateway. For example, a client wishing to retrieve a resource
directly from the origin server would create a TCP connection to port 80 of the
host "www.w3.org" and send the following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original
URI, it MUST be given as "/" (the server root).

Request Header Fields

We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For
now, let's check what Request header fields are.
The request-header fields allow the client to pass additional information about the request, and about the client
itself, to the server. These fields act as request modifiers.Here is a list of some important Request-header fields
that can be used based on the requirement:
 Accept-Charset
 Accept-Encoding
 Accept-Language
 Authorization
 Expect
 From
 Host
 If-Match
 If-Modified-Since
 If-None-Match
 If-Range
 If-Unmodified-Since
 Max-Forwards
 Proxy-Authorization
 Range
 Referer
 TE
 User-Agent
You can introduce your custom fields in case you are going to write your own custom Client and Web Server.
Examples of Request Message

Now let's put it all together to form an HTTP request to fetch hello.htm page from the web server running on
tutorialspoint.com
GET /hello.htm HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Here we are not sending any request data to the server because we are fetching a plain HTML page from the
server. Connection is a general-header, and the rest of the headers are request headers. The following example
shows how to send form data to the server using request message body:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

licenseID=string&content=string&/paramsXML=string
Here the given URL /cgi-bin/process.cgi will be used to process the passed data and accordingly, a response will
be returned. Here content-type tells the server that the passed data is a simple web form data and length will be
the actual length of the data put in the message body. The following example shows how you can pass plain XML
to your web server:
POST /cgi-bin/process.cgi HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
Host: www.tutorialspoint.com
Content-Type: text/xml; charset=utf-8
Content-Length: length
Accept-Language: en-us
Accept-Encoding: gzip, deflate
Connection: Keep-Alive

<?xml version="1.0" encoding="utf-8"?>


<string xmlns="http://clearforest.com/">string</string>
HTTP - Responses
After receiving and interpreting a request message, a server responds with an HTTP response message:
 A Status-line

 Zero or more header (General|Response|Entity) fields followed by CRLF

 An empty line (i.e., a line with nothing preceding the CRLF)


 indicating the end of the header fields

 Optionally a message-body

The following sections explain each of the entities used in an HTTP response message.

Message Status-Line

A Status-Line consists of the protocol version followed by a numeric status code and its associated textual phrase.
The elements are separated by space SP characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP Version

A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1

Status Code

The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of response and
the last two digits do not have any categorization role. There are 5 values for the first digit:

S.N. Code and Description

1 1xx: Informational
It means the request was received and the process is continuing.

2 2xx: Success
It means the action was successfully received, understood, and accepted.

3 3xx: Redirection
It means further action must be taken in order to complete the request.
4 4xx: Client Error
It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error


It means the server failed to fulfill an apparently valid request.

HTTP status codes are extensible and HTTP applications are not required to understand the meaning of all
registered status codes. A list of all the status codes has been given in a separate chapter for your reference.

Response Header Fields

We will study General-header and Entity-header in a separate chapter when we will learn HTTP header fields. For
now, let's check what Response header fields are.
The response-header fields allow the server to pass additional information about the response which cannot be
placed in the Status- Line. These header fields give information about the server and about further access to the
resource identified by the Request-URI.
 Accept-Ranges
 Age
 ETag
 Location
 Proxy-Authenticate
 Retry-After
 Server
 Vary
 WWW-Authenticate
You can introduce your custom fields in case you are going to write your own custom Web Client and Server.

Examples of Response Message

Now let's put it all together to form an HTTP response for a request to fetch the  hello.htm page from the web
server running on tutorialspoint.com
HTTP/1.1 200 OK
Date: Mon, 27 Jul 2009 12:28:53 GMT
Server: Apache/2.2.14 (Win32)
Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT
Content-Length: 88
Content-Type: text/html
Connection: Closed
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The following example shows an HTTP response message displaying error condition when the web server could
not find the requested page:
HTTP/1.1 404 Not Found
Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Connection: Closed
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>404 Not Found</title>
</head>
<body>
<h1>Not Found</h1>
<p>The requested URL /t.html was not found on this server.</p>
</body>
</html>
Following is an example of HTTP response message showing error condition when the web server encountered a
wrong HTTP version in the given HTTP request:
HTTP/1.1 400 Bad Request
Date: Sun, 18 Oct 2012 10:36:20 GMT
Server: Apache/2.2.14 (Win32)
Content-Length: 230
Content-Type: text/html; charset=iso-8859-1
Connection: Closed

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">


<html>
<head>
<title>400 Bad Request</title>
</head>
<body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.</p>
<p>The request line contained invalid characters following the protocol string.</p>
</body>
</html>
WEB CLIENTS – WEB SERVERS
HTML

HTML is the standard markup language for creating Web pages.


 HTML stands for Hyper Text Markup Language
 HTML describes the structure of Web pages using markup
 HTML elements are the building blocks of HTML pages
 HTML elements are represented by tags
 HTML tags label pieces of content such as "heading", "paragraph", "table", and so on
 Browsers do not display the HTML tags, but use them to render the content of the page
HTML Tags
HTML tags are element names surrounded by angle brackets:
<tagname>content goes here...</tagname>
Web Browsers
The purpose of a web browser (Chrome, IE, Firefox, Safari) is to read HTML documents and display them.
The browser does not display the HTML tags, but uses them to determine how to display the document:
HTML Page Structure
Below is a visualization of an HTML page structure:
The <!DOCTYPE> Declaration
The <!DOCTYPE> declaration represents the document type, and helps browsers to display web pages correctly.
It must only appear once, at the top of the page (before any HTML tags).
The <!DOCTYPE> declaration is not case sensitive.
The <!DOCTYPE> declaration for HTML is:
<!DOCTYPE html>

Complete Html Tags list with examples


 
Tag Short description

THE ROOT ELEMENT

<html> Main container


<h5>This is heading 5</h5>
<h6>This is heading 6</h6>

</body>
</html>

OUTPUT

HTML Paragraphs
HTML paragraphs are defined with the <p> tag:
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
HTML Links
HTML links are defined with the <a> tag:
Example
<a href="http://www.w3schools.com">This is a link</a>
HTML Images
HTML images are defined with the <img> tag.
The source file (src), alternative text (alt), width, and height are provided as attributes:
Example
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

Nested HTML Elements


HTML elements can be nested (elements can contain elements).
All HTML documents consist of nested HTML elements.
This example contains four HTML elements:
Example
<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

HTML Attributes
 All HTML elements can have attributes
 Attributes provide additional information about an element
 Attributes are always specified in the start tag
 Attributes usually come in name/value pairs like: name="value"
The title Attribute
Here, a title attribute is added to the <p> element. The value of the title attribute will be displayed as a tooltip when
you mouse over the paragraph:
Example
<p title="I'm a tooltip">
This is a paragraph.
</p>

The href Attribute


HTML links are defined with the <a> tag. The link address is specified in the href attribute:
Example
<a href="http://www.w3schools.com">This is a link</a>

Size Attributes
HTML images are defined with the <img> tag.
The filename of the source (src), and the size of the image (width and height) are all provided as attributes:
Example
<img src="w3schools.jpg" width="104" height="142">

The alt Attribute


The alt attribute specifies an alternative text to be used, when an image cannot be displayed.
The value of the attribute can be read by screen readers. This way, someone "listening" to the webpage, e.g. a
blind person, can "hear" the element.
Example
<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">
The HTML Style Attribute
Setting the style of an HTML element, can be done with the style attribute.
The HTML style attribute has the following syntax:
<tagname style="property:value;">
HTML Background Color
The background-color property defines the background color for an HTML element.
This example sets the background color for a page to blue:
Example
<body style="background-color: blue;">

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

</body>
HTML Text Color
The color property defines the text color for an HTML element:
Example
<h1 style="color:blue;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>
HTML Fonts
The font-family property defines the font to be used for an HTML element:
Example
<h1 style="font-family:verdana;">This is a heading</h1>
<p style="font-family:courier;">This is a paragraph.</p>
HTML Text Size
The font-size property defines the text size for an HTML element:
Example
<h1 style="font-size:300%;">This is a heading</h1>
<p style="font-size:160%;">This is a paragraph.</p>
HTML Text Alignment
The text-align property defines the horizontal text alignment for an HTML element:
Example
<h1 style="text-align:center;">Centered Heading</h1>
<p style="text-align:center;">Centered paragraph.</p>
HTML Formatting Elements
In the previous chapter, you learned about the HTML style attribute.
HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Formatting elements were designed to display special types of text:
 <b> - Bold text
 <strong> - Important text
 <i> - Italic text
 <em> - Emphasized text
 <mark> - Marked text
 <small> - Small text
 <del> - Deleted text
 <ins> - Inserted text
 <sub> - Subscript text
 <sup> - Superscript text
HTML <b> and <strong> Elements
The HTML <b> element defines bold text, without any extra importance.
Example
<b>This text is bold</b>
The HTML <strong> element defines strong text, with added semantic "strong" importance.
Example
<strong>This text is strong</strong>
HTML <i> and <em> Elements
The HTML <i> element defines italic text, without any extra importance.
Example
<i>This text is italic</i>
HTML <mark> Element
The HTML <mark> element defines marked or highlighted text:
Example
<h2>HTML <mark>Marked</mark> Formatting</h2>
HTML <ins> Element
The HTML <ins> element defines inserted (added) text.
Example
<p>My favorite <ins>color</ins> is red.</p>
HTML <sub> Element
The HTML <sub> element defines subscripted text.
Example
<p>This is <sub>subscripted</sub> text.</p>
HTML <sup> Element
The HTML <sup> element defines superscripted text.
Example
<p>This is <sup>superscripted</sup> text.</p>
HTML <blockquote> for Quotations
The HTML <blockquote> element defines a section that is quoted from another source.
HTML Comment Tags
You can add comments to your HTML source by using the following syntax:
<!-- Write your comments here -->

HTML5
Tables

Lists

Image

HTML5 control elements

HTML5 Layout Elements


Websites often display content in multiple columns (like a magazine or newspaper).
HTML5 offers new semantic elements that define the different parts of a web page:
 <header> - Defines a header for a document or a section
 <nav> - Defines a container for navigation links
 <section> - Defines a section in a document
 <article> - Defines an independent self-contained article
 <aside> - Defines content aside from the content (like a sidebar)
 <footer> - Defines a footer for a document or a section
 <details> - Defines additional details
 <summary> - Defines a heading for the <details> element

New Input Types


Controls Description

color Used for input fields that should contain a color.

date Used for input fields that should contain a date.

datetime Allows the user to select a date and time (with time zone).

datetime-local Allows the user to select a date and time (no time zone).
email Used for input fields that should contain an e-mail address.

month Allows the user to select a month and year.

number Used for input fields that should contain a numeric value.

range Used for input fields that should contain a value within a range.

search Used for search fields (a search field behaves like a regular text field).

tel Used for input fields that should contain a telephone number.

time Allows the user to select a time (no time zone).

url Used for input fields that should contain a URL address.

week Allows the user to select a week and year.

HTML FORM ELEMENTS

The <form> Element

The HTML <form> element defines a form that is used to collect user input:

<form>
.
form elements
.
</form>

An HTML form contains form elements.

Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and
more.

The <input> Element

The <input> element is the most important form element.

The <input> element can be displayed in several ways, depending on the type attribute.


Here are some examples:

Type Description

<input type="text"> Defines a one-line text input field

<input type="radio"> Defines a radio button (for selecting one of many choices)

<input type="submit"> Defines a submit button (for submitting the form)

Text Input

<input type="text"> defines a one-line input field for text input:

Example
<html>
<body>

<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>

<p>Note that the form itself is not visible.</p>

<p>Also note that the default width of a text input field is 20 characters.</p>

</body>
</html>
OUTPUT

Radio Button Input

<input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices:

<html>
<body>
<form>
<input type="radio" name="gender" value="male" checked> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
</body>
</html>

Output

The Submit Button

<input type="submit"> defines a button for submitting the form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:

<html>
<body>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>

<p>If you click the "Submit" button, the form-data will be sent to a page called "action_page.php".</p>

</body>
</html>

The Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Normally, the form data is sent to a web page on the server when the user clicks on the submit button.

In the example above, the form data is sent to a page on the server called "action_page.php". This page contains a
server-side script that handles the form data:

<form action="action_page.jsp">
The Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when submitting the form data:

<form action="action_page.php" method="get">

or:
<form action="action_page.php" method="post">
When to Use GET?

The default method when submitting form data is GET.

However, when GET is used, the submitted form data will be visible in the page address field:

When to Use POST?

Always use POST if the form data contains sensitive or personal information. The POST method does not display
the submitted form data in the page address field.

POST has no size limitations, and can be used to send large amounts of data.

The Name Attribute

Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that input field will not be sent at all.

This example will only submit the "Last name" input field:

Example
<form action="action_page.php">
  First name:<br>
  <input type="text" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>
Grouping Form Data with <fieldset>

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

<!DOCTYPE html>
<html>
<body>

<form action="action_page.php">
<fieldset>
<legend>Personal information:</legend>
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</fieldset>
</form>

</body>
</html>

The <input> Element

The most important form element is the <input> element.

The <input> element can be displayed in several ways, depending on the type attribute.


The <select> Element

The <select> element defines a drop-down list:

<html>
<body>

<form action="action_page.php">
<select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
<br><br>
<input type="submit">
</form>

</body>
</html>

The <option> elements defines an option that can be selected.

By default, the first item in the drop-down list is selected.

To define a pre-selected option, add the selected attribute to the option:

Example
<option value="fiat" selected>Fiat</option>
The <textarea> Element

The <textarea> element defines a multi-line input field (a text area):

Example
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
The <button> Element

The <button> element defines a clickable button:

Example
<button type="button" onclick="alert('Hello World!')">Click Me!</button>
Input Type Text

<input type="text"> defines a one-line text input field:

Example
<form>
  First name:<br>
  <input type="text" name="firstname"><br>
  Last name:<br>
  <input type="text" name="lastname">
</form>
Input Type Password

<input type="password"> defines a password field:

Example
<form>
  User name:<br>
  <input type="text" name="username"><br>
  User password:<br>
  <input type="password" name="psw">
</form>
Input Type Submit

<input type="submit"> defines a button for submitting form data to a form-handler.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified in the form's action attribute:


Example
<form action="action_page.jsp">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
</form>
Input Type Reset

<input type="reset"> defines a reset button that will reset all form values to their default values:

Example
<form action="action_page.php">
  First name:<br>
  <input type="text" name="firstname" value="Mickey"><br>
  Last name:<br>
  <input type="text" name="lastname" value="Mouse"><br><br>
  <input type="submit" value="Submit">
  <input type="reset">
</form>
Input Type Radio

<input type="radio"> defines a radio button.

Radio buttons let a user select ONLY ONE of a limited number of choices:

Example
<form>
  <input type="radio" name="gender" value="male" checked> Male<br>
  <input type="radio" name="gender" value="female"> Female<br>
  <input type="radio" name="gender" value="other"> Other
</form>
Input Type Checkbox

<input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example
<form>
  <input type="checkbox" name="vehicle1" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle2" value="Car"> I have a car 
</form>
Output

Input Type Button

<input type="button"> defines a button:

Example
<input type="button" onclick="alert('Hello World!')" value="Click Me!">
Input Type Date

The <input type="date"> is used for input fields that should contain a date.

Depending on browser support, a date picker can show up in the input field.

Example
<form>
  Birthday:
  <input type="date" name="bday">
</form>
Input Type Color

The <input type="color"> is used for input fields that should contain a color.

Depending on browser support, a color picker can show up in the input field.

Example
<form>
  Select your favorite color:
  <input type="color" name="favcolor">
</form>
Input Type Time
The <input type="time"> allows the user to select a time (no time zone).

Depending on browser support, a time picker can show up in the input field.

Example
<form>
  Select a time:
  <input type="time" name="usr_time">
</form>
Input Type Email

The <input type="email"> is used for input fields that should contain an e-mail address.

Depending on browser support, the e-mail address can be automatically validated when submitted.

Some smartphones recognize the email type, and adds ".com" to the keyboard to match email input.

Example
<form>
  E-mail:
  <input type="email" name="email">
</form>
Input Type Search

The <input type="search"> is used for search fields (a search field behaves like a regular text field).

Example
<form>
  Search Google:
  <input type="search" name="googlesearch">
</form>

SEMANTIC ELEMENTS

Semantic/Structural elements
Controls Description
<article> Defines an article.
<aside> Defines content aside from the page content.
<bdi> Isolates a part of text that might be formatted in a different direction from other text outside of it.
<command> Defines a command button that a user can invoke.
<details> Specifies additional details that the user can view or hide on demand.
<figcaption> Defines a caption for a <figure> element.
<figure> Specifies self-contained content.
footer> Defines a footer for a document or section.
<header> Defines a header for a document or section.
<hgroup> Group heading (<h1> to <h6>) elements.
<mark> Defines marked/highlighted text.
<meter> Defines a scalar measurement within a known range, or a fractional value.
<nav> Defines navigation links.
<output> Represents the result of a calculation.
<progress> Represents the progress of a task.
Defines what to show in browsers that do not support ruby annotations (for East Asian
<rp>
typography).
<rt> Defines an explanation/pronunciation of characters (for East Asian typography).
<ruby> Defines a ruby annotation (for East Asian typography).
<section> Defines a section in a document.
Defines a visible heading for the <details> element. The heading can be clicked to view/hide the
<summary>
details.
<time> Defines a date/time.
Semantic HTML elements are those that clearly describe their meaning in a human- and machine-
readable way.

Elements such as <header>, <footer> and <article> are all considered semantic because they


accurately describe the purpose of the element and the type of content that is inside them.
What are Semantic Elements?
HTML was originally created as a markup language to describe documents on the early internet.
As the internet grew and was adopted by more people, its needs changed.

Where the internet was originally intended for sharing scientific documents, now people wanted to
share other things as well. Very quickly, people started wanting to make the web look nicer.

Because the web was not initially built to be designed, programmers used different hacks to get
things laid out in different ways. Rather than using the <table></table> to describe information
using a table, programmers would use them to position other elements on a page.
As the use of visually designed layouts progressed, programmers started to use a generic “non-
semantic” tag like <div>. They would often give these elements a class or id attribute to describe
their purpose. For example, instead of <header> this was often written as <div class="header">.
As HTML5 is still relatively new, this use of non-semantic elements is still very common on
websites today.

List of new semantic elements


The semantic elements added in HTML5 are:

 <article>
 <aside>
 <details>
 <figcaption>
 <figure>
 <footer>
 <header>
 <main>
 <mark>
 <nav>
 <section>
 <summary>
 <time>
Elements such as <header>, <nav>, <section>, <article>, <aside>, and <footer> act more or less
like <div> elements. They group other elements together into page sections. However where
a <div> tag could contain any type of information, it is easy to identify what sort of information
would go in a semantic <header> region.
An example of semantic element layout by w3schools
Why use semantic elements?
To look at the benefits of semantic elements, here are two pieces of HTML code. This first block
of code uses semantic elements:

<header></header>
<section>
<article>
<figure>
<img>
<figcaption></figcaption>
which of these you should choose, take note of the following:
1. An article is intended to be independently distributable or reusable.

2. A section is a thematic grouping of content.

<section>
<p>Top Stories</p>
<section>
<p>News</p>
<article>Story 1</article>
<article>Story 2</article>
<article>Story 3</article>
</section>
<section>
<p>Sport</p>
<article>Story 1</article>
<article>Story 2</article>
<article>Story 3</article>
</section>
</section>
<header> and <hgroup>
The <header> element is generally found at the top of a document, a section, or an article and
usually contains the main heading and some navigation and search tools.
<header>
<h1>Company A</h1>
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
<form target="/search">
<input name="q" type="search" />
<input type="submit" />
</form>
</header>
The <hgroup> element should be used where you want a main heading with one or more
subheadings.
<hgroup>
<h1>Heading 1</h1>
<h2>Subheading 1</h2>
<h2>Subheading 2</h2>
</hgroup>
REMEMBER, that the <header> element can contain any content, but the <hgroup> element can
only contain other headers, that is <h1> to <h6> and including <hgroup>.
<aside>
The <aside> element is intended for content that is not part of the flow of the text in which it
appears, however still related in some way. This of <aside> as a sidebar to your main content.
<aside>
<p>This is a sidebar, for example a terminology definition or a short background to a historical
figure.</p>
</aside>
Before HTML5, our menus were created with <ul>’s and <li>’s. Now, together with these, we can
separate our menu items with a <nav>, for navigation between your pages. You can have any
number of <nav> elements on a page, for example, its common to have global navigation across
the top (in the <header>) and local navigation in a sidebar (in an <aside> element).
<nav>
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact us</a></li>
</ul>
</nav>
<footer>
If there is a <header> there must be a <footer>. A <footer> is generally found at the bottom of a
document, a section, or an article. Just like the <header> the content is generally
metainformation, such as author details, legal information, and/or links to related information. It is
also valid to include <section> elements within a footer.
<footer>&copy;Company A</footer>
<small>
The <small> element often appears within a <footer> or <aside> element which would usually
contain copyright information or legal disclaimers, and other such fine print. However, this is not
intended to make the text smaller. It is just describing its content, not prescribing presentation.
<footer><small>&copy;Company A</small> Date</footer>
<time>
The <time> element allows an unambiguous ISO 8601 date to be attached to a human-readable
version of that date.
<time datetime="2017-10-31T11:21:00+02:00">Tuesday, 31 October 2017</time>
Why bother with <time>? While humans can read time that can disambiguate through context in
the normal way, the computers can read the ISO 8601 date and see the date, time, and the time
zone.
<figure> and <figcaption>
<figure> is for wrapping your image content around it, and <figcaption> is to caption your image.
<figure>
<img src="https://en.wikipedia.org/wiki/File:Shadow_of_Mordor_cover_art.jpg" alt="Shadow of
Mordor" />
<figcaption>Cover art for Middle-earth: Shadow of Mordor</figcaption>
</figure>

DRAG AND DROP

Drag and Drop (DnD) is powerful User Interface concept which makes it easy to copy, reorder and deletion of items
with the help of mouse clicks. This allows the user to click and hold the mouse button down over an element, drag it
to another location, and release the mouse button to drop the element there.
To achieve drag and drop functionality with traditional HTML4, developers would either have to either have to use
complex JavaScript programming or other JavaScript frameworks like jQuery etc.
Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it
much easier to code up.
HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4 etc.

Drag and Drop Events

There are number of events which are fired during various stages of the drag and drop operation. These events are
listed below −

Sr.No Events & Description


.

1 dragstart
Fires when the user starts dragging of the object.

2 dragenter
Fired when the mouse is first moved over the target element while a drag is
occurring. A listener for this event should indicate whether a drop is allowed
over this location. If there are no listeners, or the listeners perform no
operations, then a drop is not allowed by default.

dragover
3 This event is fired as the mouse is moved over an element when a drag is
occurring. Much of the time, the operation that occurs during a listener will be
the same as the dragenter event.

dragleave
4 This event is fired when the mouse leaves an element while a drag is
occurring. Listeners should remove any highlighting or insertion markers used
for drop feedback.

5 drag
Fires every time the mouse is moved while the object is being dragged.

drop
6 The drop event is fired on the element where the drop was occurred at the end
of the drag operation. A listener would be responsible for retrieving the data
being dragged and inserting it at the drop location.

7 dragend
Fires when the user releases the mouse button while dragging an object.

Note − Note that only drag events are fired; mouse events such as mousemove are not fired during a drag
operation.

The DataTransfer Object

The event listener methods for all the drag and drop events accept Event object which has a readonly attribute
called dataTransfer.
The event.dataTransfer returns DataTransfer object associated with the event as follows −
function EnterHandler(event) {
DataTransfer dt = event.dataTransfer;
.............
}
The DataTransfer object holds data about the drag and drop operation. This data can be retrieved and set in terms
of various attributes associated with DataTransfer object as explained below −

Sr.No DataTransfer attributes and their description


.

dataTransfer.dropEffect [ = value ]
1  Returns the kind of operation that is currently selected.
 This attribute can be set, to change the selected operation.
 The possible values are none, copy, link, and move.

dataTransfer.effectAllowed [ = value ]
2  Returns the kinds of operations that are to be allowed.
 This attribute can be set, to change the allowed operations.
 The possible values are none, copy, copyLink, copyMove, link,
linkMove, move, all and uninitialized.

dataTransfer.types
3 Returns a DOMStringList listing the formats that were set in the dragstart
event. In addition, if any files are being dragged, then one of the types will be
the string "Files".

dataTransfer.clearData ( [ format ] )
4
Removes the data of the specified formats. Removes all data if the argument
is omitted.

5 dataTransfer.setData(format, data)
Adds the specified data.

6 data = dataTransfer.getData(format)
Returns the specified data. If there is no such data, returns the empty string.
7 dataTransfer.files
Returns a FileList of the files being dragged, if any.

dataTransfer.setDragImage(element, x, y)
8
Uses the given element to update the drag feedback, replacing any previously
specified feedback.

dataTransfer.addElement(element)
9
Adds the given element to the list of elements used to render the drag
feedback.

Drag and Drop Process

Following are the steps to be carried out to implement Drag and Drop operation −
Step 1 - Making an Object Draggable
Here are steps to be taken −
 If you want to drag an element, you need to set the draggable attribute to true for that element.
 Set an event listener for dragstart that stores the data being dragged.
 The event listener dragstart will set the allowed effects (copy, move, link, or some combination).
Following is the example to make an object draggable −
 Live Demo

<!DOCTYPE HTML>

<html>
<head>

<style type = "text/css">

#boxA, #boxB {
float:left;padding:10px;margin:10px; -moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px; }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>

<script type = "text/javascript">


function dragStart(ev) {
ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);

return true;
}
</script>

</head>
<body>

<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</div>

<div id = "boxA" draggable = "true"


ondragstart = "return dragStart(ev)">
<p>Drag Me</p>
</div>

<div id = "boxB">Dustbin</div>
</center>

</body>
</html>
This will produce the following result −
Step 2 - Dropping the Object
To accept a drop, the drop target has to listen to at least three events.
 The dragenter event, which is used to determine whether or not the drop target is to accept the drop.
If the drop is to be accepted, then this event has to be canceled.
 The dragover event, which is used to determine what feedback is to be shown to the user. If the
event is canceled, then the feedback (typically the cursor) is updated based on the dropEffect
attribute's value.
 Finally, the drop event, which allows the actual drop to be performed.
Following is the example to drop an object into another object −
 Live Demo

<html>
<head>
<style type="text/css">
#boxA, #boxB {
float:left;padding:10px;margin:10px;-moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px; }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>
<script type="text/javascript">
function dragStart(ev) {
ev.dataTransfer.effectAllowed='move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);
return true;
}
function dragEnter(ev) {
event.preventDefault();
return true;
}
function dragOver(ev) {
return false;
}
function dragDrop(ev) {
var src = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(src));
ev.stopPropagation();
return false;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to move the purple box into the pink box.</div>
<div id="boxA" draggable="true" ondragstart="return dragStart(event)">
<p>Drag Me</p>
</div>
<div id="boxB" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return
dragOver(event)">Dustbin</div>
</center>
</body>
</html>

AUDIO

Embedding Audio
HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document as follows.
<audio src = "foo.wav" controls autoplay>
Your browser does not support the <audio> element.
</audio>
The current HTML5 draft specification does not specify which audio formats browsers should support in the audio
tag. But most commonly used audio formats are ogg, mp3 and wav.
You can use <source&ggt; 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 −
 Live Demo

<!DOCTYPE HTML>

<html>
<body>

<audio controls autoplay>


<source src = "/html5/audio.ogg" type = "audio/ogg" />
<source src = "/html5/audio.wav" type = "audio/wav" />
Your browser does not support the <audio> element.
</audio>

</body>
</html>
This will produce the following result −

Audio Attribute Specification

The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the
control −

Sr.No Attribute & Description


.

autoplay
1
This Boolean attribute if specified, the audio will automatically begin to play
back as soon as it can do so without stopping to finish loading the data.
autobuffer
2
This Boolean attribute if specified, the audio will automatically begin buffering
even if it's not set to automatically play.

controls
3
If this attribute is present, it will allow the user to control audio playback,
including volume, seeking, and pause/resume playback.

loop
4
This Boolean attribute if specified, will allow audio automatically seek back to
the start after reaching at the end.

preload
5
This attribute specifies that the audio will be loaded at page load, and ready to
run. Ignored if autoplay is present.

src
6
The URL of the audio to embed. This is optional; you may instead use the
<source> element within the video block to specify the video to embed.

Handling Media Events

The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control
using JavaScript −

S.No Event & Description


.

1 abort
This event is generated when playback is aborted.

2 canplay
This event is generated when enough data is available that the media can be
played.

3 ended
This event is generated when playback completes.

4 error
This event is generated when an error occurs.

5 loadeddata
This event is generated when the first frame of the media has finished loading.

6 loadstart
This event is generated when loading of the media begins.

7 pause
This event is generated when playback is paused.

8 play
This event is generated when playback starts or resumes.

progress
9
This event is generated periodically to inform the progress of the downloading
the media.

10 ratechange
This event is generated when the playback speed changes.

11 seeked
This event is generated when a seek operation completes.
12 seeking
This event is generated when a seek operation begins.

13 suspend
This event is generated when loading of the media is suspended.

14 volumechange
This event is generated when the audio volume changes.

waiting
15
This event is generated when the requested operation (such as playback) is
delayed pending the completion of another operation (such as a seek).

Following is the example which allows to play the given video −


 Live Demo

<!DOCTYPE HTML>

<html>
<head>

<script type = "text/javascript">


function PlayVideo() {
var v = document.getElementsByTagName("video")[0];
v.play();
}
</script>
</head>

<body>

<form>
<video width = "300" height = "200" src = "/html5/foo.mp4">
Your browser does not support the video element.
</video>
<br />
<input type = "button" onclick = "PlayVideo();" value = "Play"/>
</form>
</body>
</html>
This will produce the following result −

Configuring Servers for Media Type

Most servers don't by default serve Ogg or mp4 media with the correct MIME types, so you'll likely need to add the
appropriate configuration for this.
AddType audio/ogg .oga
AddType audio/wav .wav
AddType video/ogg .ogv .ogg
AddType video/mp4 .mp4

VIDEO CONTROLS

HTML5 features include native audio and video support without the need for Flash.
The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set  src attribute to
identify the media source and include a controls attribute so the user can play and pause the media.

Embedding Video

Here is the simplest form of embedding a video file in your webpage −


<video src = "foo.mp4" width = "300" height = "200" controls>
Your browser does not support the <video> element.
</video>
The current HTML5 draft specification does not specify which video formats browsers should support in the video
tag. But most commonly used video formats are −
 Ogg − Ogg files with Thedora video codec and Vorbis audio codec.
 mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec.
You can use <source> tag to specify media along with media type and many other attributes. A video element
allows multiple source elements and browser will use the first recognized format −
 Live Demo

<!DOCTYPE HTML>

<html>
<body>
<video width = "300" height = "200" controls autoplay>
<source src = "/html5/foo.ogg" type ="video/ogg" />
<source src = "/html5/foo.mp4" type = "video/mp4" />
Your browser does not support the <video> element.
</video>

</body>
</html>
This will produce the following result −

Video Attribute Specification

The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the
control −

Sr.No Attribute & Description


.

autoplay
1
This Boolean attribute if specified, the video will automatically begin to play
back as soon as it can do so without stopping to finish loading the data.

autobuffer
2
This Boolean attribute if specified, the video will automatically begin buffering
even if it's not set to automatically play.

controls
3
If this attribute is present, it will allow the user to control video playback,
including volume, seeking, and pause/resume playback.

4 height
This attribute specifies the height of the video's display area, in CSS pixels.

5 loop
This Boolean attribute if specified, will allow video automatically seek back to
the start after reaching at the end.

preload
6
This attribute specifies that the video will be loaded at page load, and ready to
run. Ignored if autoplay is present.

7 poster
This is a URL of an image to show until the user plays or seeks.

src
8
The URL of the video to embed. This is optional; you may instead use the
<source> element within the video block to specify the video to embed.

9 width
This attribute specifies the width of the video's display area, in CSS pixels.

CSS3 – INLINE, EMBEDDED AND EXTERNAL STYLE SHEETS

Styling HTML with CSS3

CSS stands for Cascading Style Sheets.

CSS describes how HTML elements are to be displayed on screen, paper, or in other media.

CSS saves a lot of work. It can control the layout of multiple web pages all at once.

CSS can be added to HTML elements in 3 ways:

 Inline - by using the style attribute in HTML elements


 Internal - by using a <style> element in the <head> section
 External - by using an external CSS file

Inline CSS

An inline CSS is used to apply a unique style to a single HTML element.

An inline CSS uses the style attribute of an HTML element.


This example sets the text color of the <h1> element to blue:

<html>
<body>

<h1 style="color:blue;">This is a Blue Heading</h1>

</body>
</html>
Internal CSS

An internal CSS is used to define a style for a single HTML page.

An internal CSS is defined in the <head> section of an HTML page, within a <style> element:

<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>

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

</body>
</html>

External CSS

An external style sheet is used to define the style for many HTML pages.

With an external style sheet, you can change the look of an entire web site, by changing one file!

To use an external style sheet, add a link to it in the <head> section of the HTML page:

<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>

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

</body>
</html>

Here is how the "styles.css" looks:

body {
    background-color: powderblue;
}
h1 {
    color: blue;
}
p {
    color: red;
}
CSS Fonts

The CSS color property defines the text color to be used.

The CSS font-family property defines the font to be used.

The CSS font-size property defines the text size to be used.

<html>
<head>
<style>
h1 {
    color: blue;
    font-family: verdana;
    font-size: 300%;
}
p  {
    color: red;
    font-family: courier;
    font-size: 160%;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
CSS Border

The CSS border property defines a border around an HTML element:

Example
p {
    border: 1px solid powderblue;
}

Try it Yourself »

CSS Padding

The CSS padding property defines a padding (space) between the text and the border:

Example
p {
    border: 1px solid powderblue;
    padding: 30px;
}

Try it Yourself »

CSS Margin

The CSS margin property defines a margin (space) outside the border:

Example
p {
    border: 1px solid powderblue;
    margin: 50px;
}

Try it Yourself »

The id Attribute

To define a specific style for one special element, add an id attribute to the element:

<p id="p01">I am different</p>

then define a style for the element with the specific id:

Example
#p01 {
    color: blue;
}

The class Attribute

To define a style for a special type of elements, add a class attribute to the element:

<p class="error">I am different</p>

then define a style for the elements with the specific class:

Example
p.error {
    color: red;
}

Defining an HTML Table

An HTML table is defined with the <table> tag.

Each table row is defined with the <tr> tag. A table header is defined with the <th> tag. By default, table headings
are bold and centered. A table data/cell is defined with the <td> tag.

<html>
<body>

<table border=”1”>

  <tr>

    <th>Firstname</th>

    <th>Lastname</th>

    <th>Age</th>

  </tr>

<tr>

<td>Jill</td>

<td>Smith</td>

<td>50</td>

</tr>

<tr>

<td>Eve</td>

<td>Jackson</td>

<td>94</td>

</tr>

<tr>

<td>John</td>

<td>Doe</td>

<td>80</td>

</tr>

</table>
</body>

</html>

HTML Table - Adding a Border

If you do not specify a border for the table, it will be displayed without borders.

A border is set using the CSS border property:

Example
table, th, td {
    border: 1px solid black;
}

HTML Table - Left-align Headings

By default, table headings are bold and centered.

To left-align the table headings, use the CSS text-align property:

Example
th {
    text-align: left;
}

HTML Table - Adding Border Spacing

Border spacing specifies the space between the cells.

To set the border spacing for a table, use the CSS border-spacing property:

Example
table {
    border-spacing: 5px;
}

Table properties

 Use the CSS border property to define a border


 Use the CSS border-collapse property to collapse cell borders
 Use the CSS padding property to add padding to cells
 Use the CSS text-align property to align cell text
 Use the CSS border-spacing property to set the spacing between cells
 Use the colspan attribute to make a cell span many columns
 Use the rowspan attribute to make a cell span many rows
 Use the id attribute to uniquely define one table

Backgrounds

BORDER IMAGES.

h1{
border:2px solid blue;
padding:30px;
border-inline-width:10px;

}
border:2px dotted blue;
padding:30px;
border-inline-width:10px;

h1 {
border:2px dotted blue;
padding:30px;
border-inline-width:10px;
border-inline-start-style:solid;
}

border:double red;
padding:30px;
border-inline-width:10px;
border:double red;
padding:30px;

h1 {
border:2px solid green;
padding:30px;
border-inline-width:thin thick;
}

h1 {
border-left:10px solid red;
border-right:30px solid blue;
border-top:30px solid green;
border-bottom:30px dotted rgba(250,0,0,0.4);
padding:10px;
}

h1 {
border:2px solid green;
padding:30px;
border-inline-width:10px 40px;
}

Colors
Shadows

Text

Transformations

EXAMPLE

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 2s, transform 2s;
}

div:hover {
width: 300px;
height: 300px;
transform: rotate(180deg);
}
</style>
</head>
<body>

<h1>Transition + Transform</h1>

<p>Hover over the div element below:</p>

<div></div>

</body>
</html>
EX2:
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s, height 2s, transform 5s;
}

div:hover {
width: 500px;
height: 500px;
transform: rotate(360deg);
}
</style>
TRANSITIONS

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}

div:hover {
width: 300px;
}
</style>
</head>
<body>

<h1>The transition Property</h1>

<p>Hover over the div element below, to see the transition effect:</p>
<div></div>

</body>
</html>
Specify the Speed Curve of the Transition

The transition-timing-function property specifies the speed curve of the transition effect.

The transition-timing-function property can have the following values:

 ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)
 linear - specifies a transition effect with the same speed from start to end
 ease-in - specifies a transition effect with a slow start
 ease-out - specifies a transition effect with a slow end
 ease-in-out - specifies a transition effect with a slow start and end
 cubic-bezier(n,n,n,n) - lets you define your own values in a cubic-bezier function
<!DOCTYPE html>
<html>
<head>
<style>
div{
width: 200px;
height: 70px;
background: pink;
transition: width 2s;
}

#p1 {transition-timing-function: linear;}


#p2 {transition-timing-function: ease;}
#p3 {transition-timing-function: ease-in;}
#p4 {transition-timing-function: ease-out;}
#p5 {transition-timing-function: ease-in-out;}
div:hover {
width: 300px;
}
</style>
</head>
<body>

<h1>The transition Property</h1>

<div id="p1">linear - specifies a transition effect with the same speed from start to end</div>
<br>
<div id="p2">ease - specifies a transition effect with a slow start, then fast, then end slowly (this is default)</div>
<br>
<div id="p3">ease-in - specifies a transition effect with a slow start</div>
<br>
<div id="p4">ease-out - specifies a transition effect with a slow end</div>
<br>
<div id="p5">ease-in-out - specifies a transition effect with a slow start and end</div>
<br>
</body>
</html>

The following example has a 1 second delay before starting:


div {
  transition-delay: 1s;
}
Transition + Transformation

The following example adds a transition effect to the transformation:


div {
  transition: width 2s, height 2s, transform 2s;
}
CSS3 ANIMATION

CSS Animations
CSS allows animation of HTML elements without using JavaScript or Flash!
In this chapter you will learn about the following properties:
 @keyframes
 animation-name
 animation-duration
 animation-delay
 animation-iteration-count
 animation-direction
 animation-timing-function
 animation-fill-mode
 animation
The @keyframes Rule
When you specify CSS styles inside the @keyframes rule, the animation will gradually change from the current
style to the new style at certain times.
To get an animation to work, you must bind the animation to an element.
The following example binds the "example" animation to the <div> element. The animation will last for 4 seconds,
and it will gradually change the background-color of the <div> element from "red" to "yellow":

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}

@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
</style>
</head>
<body>
<h1>CSS Animation</h1>

<div></div>

<p><b>Note:</b> When an animation is finished, it goes back to its original style.</p>

</body>
</html>

<style>
@keyframes example {
0% {background-color: red;}
25% {background-color: yellow;}
50% {background-color: blue;}
100% {background-color: green;}
}
/* The element to apply the animation to */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
</style>
EX3:

<style>
@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}

/* The element to apply the animation to */


div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
</style>

<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 100px;
height: 100px;
background-color: red;
position: relative;
animation-name: example;
animation-duration: 4s;
animation-delay: -2s;
}

@keyframes example {
0% {background-color:red; left:0px; top:0px;}
25% {background-color:yellow; left:200px; top:0px;}
50% {background-color:blue; left:200px; top:200px;}
75% {background-color:green; left:0px; top:200px;}
100% {background-color:red; left:0px; top:0px;}
}
</style>
</head>
<body>

<h1>CSS Animation</h1>

<p>Using negative values in the animation-delay property: Here, the animation will start as if it had already been
playing for 2 seconds:</p>

<div></div>

</body>
</html>

Set How Many Times an Animation Should Run


The animation-iteration-count property specifies the number of times an animation should run.
The following example will run the animation 3 times before it stops:
div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-iteration-count: 3;
}

The following example uses the value "infinite" to make the animation continue for ever:
animation-iteration-count: infinite;

Run Animation in Reverse Direction or Alternate Cycles


The animation-direction property specifies whether an animation should be played forwards, backwards or in
alternate cycles.
The animation-direction property can have the following values:
 normal - The animation is played as normal (forwards). This is default
 reverse - The animation is played in reverse direction (backwards)
 alternate - The animation is played forwards first, then backwards
 alternate-reverse - The animation is played backwards first, then forwards
The following example will run the animation in reverse direction (backwards):

Example
div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-direction: reverse;
}
The following example uses the value "alternate" to make the animation run forwards first, then backwards:
Example
div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate;
}
The following example uses the value "alternate-reverse" to make the animation run backwards first, then forwards:
Example
div {
  width: 100px;
  height: 100px;
  position: relative;
  background-color: red;
  animation-name: example;
  animation-duration: 4s;
  animation-iteration-count: 2;
  animation-direction: alternate-reverse;
}
Specify the fill-mode For an Animation
CSS animations do not affect an element before the first keyframe is played or after the last keyframe is played.
The animation-fill-mode property can override this behavior.
The animation-fill-mode property specifies a style for the target element when the animation is not playing (before it
starts, after it ends, or both).
The animation-fill-mode property can have the following values:
 none - Default value. Animation will not apply any styles to the element before or after it is executing
 forwards - The element will retain the style values that is set by the last keyframe (depends on animation-
direction and animation-iteration-count)
 backwards - The element will get the style values that is set by the first keyframe (depends on animation-
direction), and retain this during the animation-delay period
 both - The animation will follow the rules for both forwards and backwards, extending the animation
properties in both directions
The following example lets the <div> element retain the style values from the last keyframe when the animation
ends:
Example
div {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  animation-name: example;
  animation-duration: 3s;
  animation-fill-mode: forwards;
}

Animation Shorthand Property


The example below uses six of the animation properties:
Example
div {
  animation-name: example;
  animation-duration: 5s;
  animation-timing-function: linear;
  animation-delay: 2s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

UNIT II - CLIENT SIDE SCRIPTINGWITHFRAMEWORK


Java Script: An introduction to JavaScript–JavaScript DOM Model-Validation-Built-in objects-Event
HandlingDHTML with JavaScript– AngularJS:Introduction to AngularJS –Directives –Filters - Directives in DOM -
Events – Expression – Controller & Scope – Module & API.

JAVA SCRIPT: AN INTRODUCTION TO JAVASCRIPT

Differences between Client-side and Server-side Scripting

Client-side Environment

The client-side environment used to run scripts is usually a browser. The processing takes place on the end users
computer. The source code is transferred from the web server to the users computer over the internet and run
directly in the browser.

The scripting language needs to be enabled on the client computer. Sometimes if a user is conscious of security
risks they may switch the scripting facility off. When this is the case a message usually pops up to alert the user
when script is attempting to run.

EX. : javascript,vbscript

Server-side Environment

The server-side environment that runs a scripting language is a web server. A user's request is fulfilled by
running a script directly on the web server to generate dynamic HTML pages. This HTML is then sent to the client
browser. It is usually used to provide interactive web sites that interface to databases or other data stores on the
server.

This is different from client-side scripting where scripts are run by the viewing web browser, usually in JavaScript.
The primary advantage to server-side scripting is the ability to highly customize the response based on the user's
requirements, access rights, or queries into data stores.

EX. : JSP, ASP, PHP, Servlet etc.

CLICK HERE : JAVA SCRIPT BASICS

JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.


Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must learn:

   1. HTML to define the content of web pages

   2. CSS to specify the layout of web pages

4. JavaScript to program the behavior of web pages

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript in Body</h2>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = "My First JavaScript";

</script>

</body>

</html>
OUTPUT

JavaScript Output
JavaScript Display Possibilities

JavaScript can "display" data in different ways:

 Writing into an HTML element, using innerHTML.


 Writing into the HTML output using document.write().
 Writing into an alert box, using window.alert().
 Writing into the browser console, using console.log().

Ex2:

<!DOCTYPE html>

<html>
<body>

<h2>My First Web Page</h2>

<p>My first paragraph.</p>

<p>Never call document.write after the document has finished loading.

It will overwrite the whole document.</p>

<script>

document.write(5 + 6);

</script>

</body>

</html>

JavaScript Introduction
JavaScript Can Change HTML Content
One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to
"Hello JavaScript":

EX:

<!DOCTYPE html>
<html>
<body>

<h2>My First JavaScript</h2>

<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>

<p id="demo"></p>

</body>
</html>

JavaScript syntax is the set of rules, how JavaScript programs are constructed:

// How to create variables:


var x;
let y;

// How to use variables:


x = 5;
y = 6;
let z = x + y;
JavaScript Values

The JavaScript syntax defines two types of values:

 Fixed values
 Variable values

Fixed values are called Literals.

Variable values are called Variables.

JavaScript Literals

The two most important syntax rules for fixed values are:

1. Numbers are written with or without decimals:

10.50

1001

Try it Yourself »

2. Strings are text, written within double or single quotes:

"John Doe"

'John Doe'

JavaScript Variables

In a programming language, variables are used to store data values.

JavaScript uses the keywords var, let and const to declare variables.


An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

let x;
x = 6;

JAVASCRIPT OWN EXAMPLES


<html>
<head>
<script>
function disp()
{
document.writeln("<H1>HELLO WELCOME TO JAVA SCRIPT - GET AFTER CLICK ON THE WINDOW</H1>");
}

</script>
<body onclick="disp()">

</body>
</html>

EX2:

<body onmouseover="disp()">

EX3: Addition of two numbers


<html>
<head>
<script>
function disp()
{
var a=window.prompt("Enter number1");
let b=window.prompt("Enter number2");
c=parseInt(a)+parseInt(b);
document.writeln("RESULT of ADD :"+c);
}
</script>
<body onload="disp()">
</body>
</html>

Inputs

Output
JavaScript DOM Model

VALIDATION

Form Controls and validation


<html>
<body><h1>Welcome to Student Registration Page</h1></body>
<form name="frm">
Enter UserName<br>
<input type="text" name ="t1" value=""><br>
Enter Password<br>
<input type="password" name ="tp" value=""><br>

Validate UserName and Password<br>


<input type="button" name="b2" value="Validate UserName and Password" onclick="validate()"><br>
Address<br>
<textarea name="ta1" rows="5" cols="50"></textarea><br>
Enter Internal Mark<br>
<input type="text" name="t2" value=""><br>
Enter External Mark<br>
<input type="text" name="t3" value=""><br>
Enter Total Mark<br>
<input type="text" name="t4" value=""><br>
Find Total Mark<br>
<input type="button" name="b1" value="Find Total" onclick="total()"><br>

Select Gender<br>
<input type="radio" name="r1" value="1" onclick="gender(this.value)">Female <br>
<input type="radio" name="r1" value="2" onclick="gender(this.value)">Male <br>

Select Hobbies<br>
<input type="checkbox" name="c1" value="1" onclick="hobbies(this.value)">Reading Books <br>
<input type="checkbox" name="c1" value="2" onclick="hobbies(this.value)">Watching TV<br>
<input type="checkbox" name="c1" value="3" onclick="hobbies(this.value)">Playing Cricket<br>

Highest Qualification<br>
<select name="course">
<option value="1" onclick="qual(this.value)">UG</option>
<option value="2" onclick="qual(this.value)">PG</option>
<option value="3" onclick="qual(this.value)">Ph.D</option>
</select><br>
Area Of Interest<br>
<select name="area" multiple>
<option>OS</option>
<option>DS</option>
</select>
</form>
<script>
function validate()
{
var name,pwd;
name=frm.t1.value;
pwd=frm.tp.value;
if(name=="usha" && pwd=="usha")
window.alert("Correct Username and Password");
else
window.alert("Invalid username and password - Try again");
}

function total()
{
var a,b;
a=frm.t2.value;
b=frm.t3.value;
frm.t4.value=parseInt(a)+parseInt(b);
}

function gender(gen)
{
if(gen==1)
window.alert("Female");
else
window.alert("Male");
}

function hobbies(hob)
{
if(hob==1)
window.alert("You selected Reading books");
else if(hob==2)
window.alert("You selected Watching TV");
else
window.alert("You selected Playing Cricket");
}

function qual(q)
{
if(q==1)
window.alert("Highest qualification is UG");
else if(q==2)
window.alert("Highest qualification is PG");
else
window.alert("Highest qualification is Ph.D");
}
</script>
</body>
</html>

OUTPUT

BUILT-IN OBJECTS

Click Here : Java Script Built-In Objects


Outline
12.1 Introduction
12.2 Thinking About Objects
12.3 Math Object
12.4 String Object
12.4.1 Fundamentals of Characters and Strings
12.4.2 Methods of the String Object
12.4.3 Character-Processing Methods
12.4.4 Searching Methods
12.4.5 Splitting Strings and Obtaining Substrings
12.4.6 XHTML Markup Methods
12.5 Date Object
12.6 Boolean and Number Objects
12.7 document Object
12.8 window Object
12.9 Using Cookies
12.10 Final JavaScript Example
12.11 Web Resources
String Object
• JavaScript’s string and character-processing capabilities
• Appropriate for processing names, addresses, credit card information, etc.
• 12.4.1 Fundamentals of Characters and Strings
– Characters
Fundamental building blocks of JavaScript programs
– String
Series of characters treated as a single unit
Methods of the String Object
Date Object
• Provides methods for date and time manipulations

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ) as
shown below.
Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to
get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time
or UTC (universal, or GMT) time.
The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond
precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so
JavaScript can represent date and time till the year 275755.
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 ])
Note − Parameters in the brackets are always optional.
Here is a description of the parameters −
 No Argument − With no arguments, the Date() constructor creates a Date object set to the current
date and time.
 milliseconds − When one numeric argument is passed, it is taken as the internal numeric
representation of the date in milliseconds, as returned by the getTime() method. For example,
passing the argument 5000 creates a date that represents five seconds past midnight on 1/1/70.
 datestring − When one string argument is passed, it is a string representation of a date, in the
format accepted by the Date.parse() method.
 7 agruments − To use the last form of the constructor shown above. Here is a description of each
argument −
o year − Integer value representing the year. For compatibility (in order to avoid the Y2K
problem), you should always specify the year in full; use 1998, rather than 98.
o month − Integer value representing the month, beginning with 0 for January to 11 for
December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-hour scale).
o minute − Integer value representing the minute segment of a time reading.
o second − Integer value representing the second segment of a time reading.
o millisecond − Integer value representing the millisecond segment of a time reading.

Date Properties

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

Sr.No. Property & Description

1 constructor

Specifies the function that creates an object's prototype.

2 prototype

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

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

Date Methods

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


Sr.No Method & Description
.

1 Date()

Returns today's date and time

2 getDate()

Returns the day of the month for the specified date according to local time.

3 getDay()

Returns the day of the week for the specified date according to local time.

4 getFullYear()

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

5 getHours()

Returns the hour in the specified date according to local time.

6 getMilliseconds()

Returns the milliseconds in the specified date according to local time.

7 getMinutes()

Returns the minutes in the specified date according to local time.

8 getMonth()

Returns the month in the specified date according to local time.

9 getSeconds()

Returns the seconds in the specified date according to local time.

10 getTime()
Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()

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

12 getUTCDate()

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

13 getUTCDay()

Returns the day of the week in the specified date according to universal time.

14 getUTCFullYear()

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

15 getUTCHours()

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

16 getUTCMilliseconds()

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

17 getUTCMinutes()

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

18 getUTCMonth()

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

19 getUTCSeconds()

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


20 getYear()

Deprecated - Returns the year in the specified date according to local time.
Use getFullYear instead.

21 setDate()

Sets the day of the month for a specified date according to local time.

22 setFullYear()

Sets the full year for a specified date according to local time.

23 setHours()

Sets the hours for a specified date according to local time.

24 setMilliseconds()

Sets the milliseconds for a specified date according to local time.

25 setMinutes()

Sets the minutes for a specified date according to local time.

26 setMonth()

Sets the month for a specified date according to local time.

27 setSeconds()

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

28 setTime()

Sets the Date object to the time represented by a number of milliseconds since
January 1, 1970, 00:00:00 UTC.

29 setUTCDate()
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 automatically converts number literals to instances of
the number class.
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument cannot be converted into a
number, it returns NaN (Not-a-Number).

Number Properties

Here is a list of each property and their description.

Sr.No Property & Description


.

1 MAX_VALUE

The largest possible value a number in JavaScript can have


1.7976931348623157E+308

2 MIN_VALUE

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

3 NaN

Equal to a value that is not a number.

4 NEGATIVE_INFINITY

A value that is less than MIN_VALUE.

5 POSITIVE_INFINITY

A value that is greater than MAX_VALUE

6 prototype
A static property of the Number object. Use the prototype property to assign
new properties and methods to the Number object in the current document

7 constructor

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

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

Number Methods

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

Sr.No Method & Description


.

1 toExponential()

Forces a number to display in exponential notation, even if the number is in


the range in which JavaScript normally uses standard notation.

2 toFixed()

Formats a number with a specific number of digits to the right of the decimal.

3 toLocaleString()

Returns a string value version of the current number in a format that may vary
according to a browser's local settings.

4 toPrecision()

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

5 toString()
Returns the string representation of the number's value.

6 valueOf()

Returns the number's value.

JavaScript - The Boolean Object


The Boolean object represents two values, either "true" or "false". If value parameter is omitted or is 0, -0, null,
false, NaN, undefined, or the empty string (""), the object has an initial value of false.
Syntax
Use the following syntax to create a boolean object.
var val = new Boolean(value);

Boolean Properties

Here is a list of the properties of Boolean object −

Sr.No. Property & Description

1 constructor

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

2 prototype

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

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

Boolean Methods

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

Sr.No Method & Description


.

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

2 toString()

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

3 valueOf()

Returns the primitive value of the Boolean object.

Math Object
• Allow the programmer to perform many common mathematical calculations
Here is a list of the methods associated with Math object and their description
Sr.No Method & Description
.

1 abs()

Returns the absolute value of a number.

2 acos()

Returns the arccosine (in radians) of a number.

3 asin()

Returns the arcsine (in radians) of a number.

4 atan()

Returns the arctangent (in radians) of a number.

5 atan2()

Returns the arctangent of the quotient of its arguments.

6 ceil()

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

7 cos()

Returns the cosine of a number.

8 exp()

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

9 floor()

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


JavaScript Arrays

An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

Syntax:
const array_name = [item1, item2, ...];      
Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>

<p id="demo"></p>

<script>
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>

Output

You can also create an array, and then provide the elements:

Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

Example
const cars = new Array("Saab", "Volvo", "BMW");

The Array object lets you store multiple values in a single variable. It stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Syntax
Use the following syntax to create an Array object −
var fruits = new Array( "apple", "orange", "mango" );

The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array
constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.
You can create array by simply assigning values as follows −
var fruits = [ "apple", "orange", "mango" ];
You will use ordinal numbers to access and to set values inside an array as follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element

Array Properties

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

Sr.No Property & Description


.

1 constructor

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

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

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

4 length

Reflects the number of elements in an array.

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

Array Methods

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

Sr.No Method & Description


.

1 concat()

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

2 every()

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

3 filter()

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

4 forEach()

Calls a function for each element in the array.

5 indexOf()

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

6 join()

Joins all elements of an array into a string.

7 lastIndexOf()
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100

The 'with' Keyword

The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or methods.


The object specified as an argument to with becomes the default object for the duration of the block that follows.
The properties and methods for the object can be used without naming the object.
Syntax
The syntax for with object is as follows −
with (object) {
properties used without the object name and dot
}
Example
Try the following example.
 Live Demo

<html>
<head>
<title>User-defined objects</title>
<script type = "text/javascript">
// Define a function which will work as a method
function addPrice(amount) {
with(this) {
price = amount;
}
}
function book(title, author) {
this.title = title;
this.author = author;
this.price = 0;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type = "text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");


document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100

EVENT HANDLING DHTML WITH JAVASCRIPT


JavaScript Events

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, js react over
these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js
handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed on
the event.

Some of the HTML events and their event handlers are:

Mouse events:

Event Performed Event Handler Description

click onclick When mouse click on an element

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

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

mousemove onmousemove When the mouse movement takes place.

Keyboard events:

Event Performed Event Handler Description

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

Form events:
Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

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

Window/Document events

Event Performed Event Handler Description

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

Let's discuss some examples over events and their handlers.

Click Event – Text box validation

<html>

<script>

function validate()

if(frm.uname.value=="")
window.alert("enter your name in textbox");

else

document.writeln(frm.uname.value);

</script>

<body>

<form name="frm">

<input type="text" value="" name="uname">

<input type="button" value="Next" onclick="validate()">

</form>

</body>

</html>

Option/radio button validation

<html>
<script>

function disp()

if(frm.gender.value=="")

window.alert("Select any one value");

else

document.writeln(frm.gender.value);

</script>

<body>

<form name="frm">

<input type="radio" value="Male" name="gender">Male

<input type="radio" value="Female" name="gender">FeMale

<input type="button" value="Next" onclick="disp()">

</form>

</body>

</html>
Combobox validation

<html>

<script>

function disp()

if(frm.branch.value=="None")

window.alert("Select your dept");

else

document.writeln("you belongs to"+frm.branch.value);

</script>

<body>

<form name="frm">
<select name="branch">

<option value="None">None</option>

<option value="AI">AI</option>

<option value="CSE">CSE</option>

<option value="ECE">ECE</option>

</select>

<input type="button" value="Next" onclick="disp()">

</form>

</body>

</html>

DHTML page using java script – Mouseover event

<html>

<script>

function disp()

{
document.body.style.backgroundColor="red";

document.getElementById("t1").value="red";

function disp1()

document.body.style.backgroundColor="blue";

document.getElementById("t1").value="blue";

</script>

<body>

<input type="button" value="SET Red Background" onmouseover="disp()">

<input type="button" value="SET Blue Background" onmouseover="disp1()">

<input type="text" id="t1">

</body>

</html>
ANGULARJS:INTRODUCTION TO ANGULARJS
AngularJS Introduction

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.

AngularJS extends HTML attributes with Directives, and binds data to HTML with Expressions.

AngularJS is a JavaScript Framework

AngularJS is a JavaScript framework written in JavaScript.

AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

AngularJS Extends HTML

AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS application.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-bind directive binds application data to the HTML view.

Ex:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">

<p>Input something in the input box:</p>


<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>

</div>

</body>
</html>
output

Example explained:

AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of an AngularJS application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds the content of the <p> element to the application variable name.

AngularJS Directives

As you have already seen, AngularJS directives are HTML attributes with an ng prefix.

The ng-init directive initializes AngularJS application variables.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='John'">

<p>The name is <span ng-bind="firstName"></span></p>

</div>

</body>
</html>
Output

AngularJS Expressions

AngularJS expressions are written inside double braces: {{ expression }}.

AngularJS will "output" data exactly where the expression is written:

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>
AngularJS expressions bind AngularJS data to HTML the same way as the ng-bind directive.

AngularJS Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
  <p>Name: <input type="text" ng-model="name"></p>
  <p>{{name}}</p>
</div>

</body>
</html>

AngularJS Applications

AngularJS modules define AngularJS applications.

AngularJS controllers control AngularJS applications.

The ng-app directive defines the application, the ng-controller directive defines the controller.

AngularJS Example
<!DOCTYPE html>

<html>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body>

<p>Try to change the names.</p>

<div ng-app="myApp" ng-controller="myCtrl">


First Name: <input type="text" ng-model="firstName"><br>

Last Name: <input type="text" ng-model="lastName"><br>

<br>

Full Name: {{firstName + " " + lastName}}

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.firstName= "John";

$scope.lastName= "Doe";

});

</script>

</body>

</html>

AngularJS modules define applications:


AngularJS Module
var app = angular.module('myApp', []);

AngularJS controllers control applications:

AngularJS Controller
app.controller('myCtrl', function($scope) {
  $scope.firstName= "John";
  $scope.lastName= "Doe";
});

AngularJS Strings

AngularJS strings are like JavaScript strings:

Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="firstName='John';lastName='Doe'">

<p>The full name is: {{ firstName + " " + lastName }}</p>

</div>

</body>
</html>
DIRECTIVES

Adding a Directive

AngularJS has a set of built-in directives which you can use to add functionality to your application.

For a full reference, visit our AngularJS directive reference.

In addition you can use the module to add your own directives to your applications:

Example
<div ng-app="myApp" w3-test-directive></div>

<script>
var app = angular.module("myApp", []);

app.directive("w3TestDirective", function() {
  return {
    template : "I was made in a directive constructor!"
  };
});
</script>

AngularJS Objects

AngularJS objects are like JavaScript objects:

Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">

<p>The name is {{ person.lastName }}</p>

</div>

</body>
</html>

AngularJS Arrays

AngularJS arrays are like JavaScript arrays:

Example

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="points=[1,15,19,2,40]">

<p>The third result is {{ points[2] }}</p>


</div>

</body>
</html>

AngularJS Expressions vs. JavaScript Expressions

Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.

Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.

AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.

AngularJS expressions support filters, while JavaScript expressions do not.

Adding a Controller

Add a controller to your application, and refer to the controller with the ng-controller directive:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>

</body>
</html>

FILTERS
AngularJS Filters

Filters can be added in AngularJS to format data.

AngularJS Filters

AngularJS provides filters to transform data:

 currency Format a number to a currency format.


 date Format a date to a specified format.
 filter Select a subset of items from an array.
 json Format an object to a JSON string.
 limitTo Limits an array/string, into a specified number of elements/characters.
 lowercase Format a string to lower case.
 number Format a number to a string.
 orderBy Orders an array by an expression.
 uppercase Format a string to upper case.

Adding Filters to Expressions

Filters can be added to expressions by using the pipe character |, followed by a filter.

The uppercase filter format strings to upper case:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>


</div>

<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>

</body>
</html>

The lowercase filter format strings to lower case:

Example
<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | lowercase }}</p>

</div>

Filter an Array Based on User Input

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a
filter.

Type a letter in the input field, and the list will shrink/grow depending on the match:
 Jani

 Carl

 Margareth

 Hege

 Joe

 Gustav

 Birgit

 Mary

 Kai

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Type a letter in the input field:</p>

<p><input type="text" ng-model="test"></p>

<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>

<p>The list will only consists of names matching the filter.</p>

</body>
</html>
DIRECTIVES IN DOM
AngularJS Directives

❮ PreviousNext ❯

AngularJS lets you extend HTML with new attributes called Directives.

AngularJS has a set of built-in directives which offers functionality to your applications.

AngularJS also lets you define your own directives.

AngularJS Directives

AngularJS directives are extended HTML attributes with the prefix ng-.

The ng-app directive initializes an AngularJS application.

The ng-init directive initializes application data.

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

Read about all AngularJS directives in our AngularJS directive reference.

Example
<div ng-app="" ng-init="firstName='John'">

<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>

</div>

Try it Yourself »

The ng-app directive also tells AngularJS that the <div> element is the "owner" of the AngularJS application.
Data Binding

The {{ firstName }} expression, in the example above, is an AngularJS data binding expression.

Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

In the next example two text fields are bound together with two ng-model directives:

Example
<div ng-app="" ng-init="quantity=1;price=5">

Quantity: <input type="number" ng-model="quantity">
Costs:    <input type="number" ng-model="price">

Total in dollar: {{ quantity * price }}

</div>

Try it Yourself »

Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.

Repeating HTML Elements

The ng-repeat directive repeats an HTML element:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="names=['Jani','Hege','Kai']">


<p>Looping with ng-repeat:</p>
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>

</body>
</html>

The ng-repeat directive actually clones HTML elements once for each item in a collection.

The ng-repeat directive used on an array of objects:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="names=[


{name:'Jani',country:'Norway'},
{name:'Hege',country:'Sweden'},
{name:'Kai',country:'Denmark'}]">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}</li>
</ul>

</div>

</body>
</html>

The ng-app Directive

The ng-app directive defines the root element of an AngularJS application.

The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded.

The ng-init Directive

The ng-init directive defines initial values for an AngularJS application.

Normally, you will not use ng-init. You will use a controller or module instead.

You will learn more about controllers and modules later.


The ng-model Directive

The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

The ng-model directive can also:

 Provide type validation for application data (number, email, required).


 Provide status for application data (invalid, dirty, touched, error).
 Provide CSS classes for HTML elements.
 Bind HTML elements to HTML forms.

Read more about the ng-model directive in the next chapter.

Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives.

New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must
use - separated name, w3-test-directive:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>

</body>
</html>

You can invoke a directive by using:

 Element name
 Attribute
 Class
 Comment

The examples below will all produce the same result:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
template : "<h1>Made by a directive!</h1>"
};
});
</script>

</body>
</html>

Attribute
Class

Comment
Restrictions

You can restrict your directives to only be invoked by some of the methods.

Example

By adding a restrict property with the value "A", the directive can only be invoked by attributes:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">

<w3-test-directive></w3-test-directive>

<div w3-test-directive></div>

<script>
var app = angular.module("myApp", []);
app.directive("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});
</script>

<p><strong>Note:</strong> By setting the <strong>restrict</strong> property to "A", only the HTML


element with the "w3-test-directive" attribute has invoked the directive.</p>

</body>
</html>

The legal restrict values are:

 E for Element name


 A for Attribute
 C for Class
 M for Comment

By default the value is EA, meaning that both Element names and attribute names can invoke the directive.

EVENTS
AngularJS has its own HTML events directives.

AngularJS Events

You can add AngularJS event listeners to your HTML elements by using one or more of these directives:

 ng-blur
 ng-change
 ng-click
 ng-copy
 ng-cut
 ng-dblclick
 ng-focus
 ng-keydown
 ng-keypress
 ng-keyup
 ng-mousedown
 ng-mouseenter
 ng-mouseleave
 ng-mousemove
 ng-mouseover
 ng-mouseup
 ng-paste

The event directives allows us to run AngularJS functions at certain user events.

An AngularJS event will not overwrite an HTML event, both events will be executed.

Mouse Events

Mouse events occur when the cursor moves over an element, in this order:

1. ng-mouseover
2. ng-mouseenter
3. ng-mousemove
4. ng-mouseleave
Or when a mouse button is clicked on an element, in this order:

1. ng-mousedown
2. ng-mouseup
3. ng-click

You can add mouse events on any HTML element.

Example

Increase the count variable when the mouse moves over the H1 element:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>

<h2>{{ count }}</h2>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>

The ng-click Directive

The ng-click directive defines AngularJS code that will be executed when the element is being clicked.

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<button ng-click="count = count + 1">Click Me!</button>

<p>{{ count }}</p>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>

</body>
</html>

EXPRESSION
AngularJS Expressions

AngularJS binds data to HTML using Expressions.

AngularJS Expressions

AngularJS expressions can be written inside double braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-bind="expression".

AngularJS will resolve the expression, and return the result exactly where the expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and
variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="">
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>

If you remove the ng-app directive, HTML will display the expression as it is, without solving it:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div>
  <p>My first expression: {{ 5 + 5 }}</p>
</div>

</body>
</html>

Ex:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<p>Change the value of the input field:</p>

<div ng-app="" ng-init="myCol='lightblue'">

<input style="background-color:{{myCol}}" ng-model="myCol">

</div>

<p>AngularJS resolves the expression and returns the result.</p>

<p>The background color of the input box will be whatever you write in the input field.</p>

</body>
</html>
AngularJS Numbers

AngularJS numbers are like JavaScript numbers:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="" ng-init="quantity=1;cost=5">


<p>Total in dollar: {{ quantity * cost }}</p>
</div>

</body>
</html>

CONTROLLER & SCOPE


AngularJS Controllers

AngularJS controllers control the data of AngularJS applications.

AngularJS controllers are regular JavaScript Objects.

AngularJS Controllers

AngularJS applications are controlled by controllers.

The ng-controller directive defines the application controller.

A controller is a JavaScript Object, created by a standard JavaScript object constructor.

AngularJS Example
<div ng-app="myApp" ng-controller="myCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
});
</script>

Try it Yourself »

Application explained:

The AngularJS application is defined by  ng-app="myApp". The application runs inside the <div>.
The ng-controller="myCtrl" attribute is an AngularJS directive. It defines a controller.

The myCtrl function is a JavaScript function.

AngularJS will invoke the controller with a $scope object.

In AngularJS, $scope is the application object (the owner of application variables and functions).

The controller creates two properties (variables) in the scope (firstName and lastName).

The ng-model directives bind the input fields to the controller properties (firstName and lastName).

ADVERTISEMENT

Controller Methods

The example above demonstrated a controller object with two properties: lastName and firstName.

A controller can also have methods (variables as functions):

AngularJS Example
<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
  $scope.fullName = function() {
    return $scope.firstName + " " + $scope.lastName;
  };
});
</script>

Try it Yourself »

Controllers In External Files

In larger applications, it is common to store controllers in external files.

Just copy the code between the <script> tags into an external file named personController.js:

AngularJS Example
<div ng-app="myApp" ng-controller="personCtrl">

First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}

</div>

<script src="personController.js"></script>

Try it Yourself »

Another Example

For the next example we will create a new controller file:

angular.module('myApp', []).controller('namesCtrl', function($scope) {


  $scope.names = [
    {name:'Jani',country:'Norway'},
    {name:'Hege',country:'Sweden'},
    {name:'Kai',country:'Denmark'}
  ];
});

Save the file as namesController.js:

And then use the controller file in an application:

AngularJS Example
<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
  <li ng-repeat="x in names">
    {{ x.name + ', ' + x.country }}
  </li>
</ul>

</div>

<script src="namesController.js"></script>

Adding a Controller

Add a controller to your application, and refer to the controller with the ng-controller directive:

Example
<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script>

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
});
</script>

AngularJS Scope

The scope is the binding part between the HTML (view) and the JavaScript (controller).

The scope is an object with the available properties and methods.

The scope is available for both the view and the controller.

How to Use the Scope?

When you make a controller in AngularJS, you pass the $scope object as an argument:

Example

Properties made in the controller, can be referred to in the view:

<div ng-app="myApp" ng-controller="myCtrl">

<h1>{{carname}}</h1>

</div>

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
  $scope.carname = "Volvo";
});

</script>

Try it Yourself »

When adding properties to the $scope object in the controller, the view (HTML) gets access to these properties.
In the view, you do not use the prefix $scope, you just refer to a property name, like {{carname}}.

Understanding the Scope

If we consider an AngularJS application to consist of:

 View, which is the HTML.


 Model, which is the data available for the current view.
 Controller, which is the JavaScript function that makes/changes/removes/controls the data.

Then the scope is the Model.

The scope is a JavaScript object with properties and methods, which are available for both the view and the
controller.

Example

If you make changes in the view, the model and the controller will be updated:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">

<input ng-model="name">

<h1>My name is {{name}}</h1>

</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.name = "John Doe";
});
</script>

<p>When you change the name in the input field, the changes will affect the model, and it will also affect
the name property in the controller.</p>

</body>
</html>

MODULE & API.

Modules and Controllers in Files

It is common in AngularJS applications to put the module and the controllers in JavaScript files.

In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:

Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script src="myApp.js"></script>
<script src="myCtrl.js"></script>

</body>
</html>

Try it Yourself »

myApp.js
var app = angular.module("myApp", []);

The [] parameter in the module definition can be used to define dependent modules.

Without the [] parameter, you are not creating a new module, but retrieving an existing one.

myCtrl.js
app.controller("myCtrl", function($scope) {
  $scope.firstName = "John";
  $scope.lastName= "Doe";
});

Functions can Pollute the Global Namespace

Global functions should be avoided in JavaScript. They can easily be overwritten or destroyed by other scripts.

AngularJS modules reduces this problem, by keeping all functions local to the module.
When to Load the Library

While it is common in HTML applications to place scripts at the end of the <body> element, it is recommended
that you load the AngularJS library either in the <head> or at the start of the <body>.

This is because calls to angular.module can only be compiled after the library has been loaded.

Example
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
  $scope.firstName = "John";
  $scope.lastName = "Doe";
});
</script>

</body>
</html>

Try it Yourself »

AngularJS Modules

❮ PreviousNext ❯

An AngularJS module defines an application.


The module is a container for the different parts of an application.

The module is a container for the application controllers.

Controllers always belong to a module.

Creating a Module

A module is created by using the AngularJS function angular.module

<div ng-app="myApp">...</div>

<script>

var app = angular.module("myApp", []);

</script>

AngularJS API

API stands for Application Programming Interface.

AngularJS Global API

The AngularJS Global API is a set of global JavaScript functions for performing common tasks like:

 Comparing objects
 Iterating objects
 Converting data

The Global API functions are accessed using the angular object.

Below is a list of some common API functions:

API Description
angular.lowercase() Converts a string to lowercase

angular.uppercase() Converts a string to uppercase

angular.isString() Returns true if the reference is a string

angular.isNumber() Returns true if the reference is a number

angular.lowercase()
Example
<div ng-app="myApp" ng-controller="myCtrl">
  <p>{{ x1 }}</p>
  <p>{{ x2 }}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.x1 = "JOHN";
  $scope.x2 = angular.lowercase($scope.x1);
});
</script>

angular.uppercase()
Example
<div ng-app="myApp" ng-controller="myCtrl">
  <p>{{ x1 }}</p>
  <p>{{ x2 }}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.x1 = "John";
  $scope.x2 = angular.uppercase($scope.x1);
});
</script>

angular.isString()
Example
<div ng-app="myApp" ng-controller="myCtrl">
  <p>{{ x1 }}</p>
  <p>{{ x2 }}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.x1 = "JOHN";
  $scope.x2 = angular.isString($scope.x1);
});
</script>

Try it Yourself »

angular.isNumber()
Example
<div ng-app="myApp" ng-controller="myCtrl">
  <p>{{ x1 }}</p>
  <p>{{ x2 }}</p>
</div>

You might also like