Professional Documents
Culture Documents
Unit 1 and 2-Wt-6th Sem Ai&Ds
Unit 1 and 2-Wt-6th Sem Ai&Ds
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.
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.
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.
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.
Now, let's see the comparison chart between client and server. We are comparing both terms based on some
characteristics.
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?
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.
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.
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.
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.
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.
2 Authentication Yes No
3 Protocol TCP UDP
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.
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.
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.
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.
.com Commercial
.edu Educational
.gov US Government
.int Organization
.mil US Military
Domain name country codes include, but are not limited to:
.au Australia
.de Germany
.fr France
.nl Netherlands
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.
A Start-line
Optionally a message-body
In the following sections, we will explain each of the entities used in an HTTP message.
Message Start-Line
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
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.
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
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
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:
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.
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.
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.
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
</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">
</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>
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">
<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
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.
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.
url Used for input fields that should contain a URL address.
<form>
.
form elements
.
</form>
Form elements are different types of input elements, like text fields, checkboxes, radio buttons, submit buttons, and
more.
Type Description
<input type="radio"> Defines a radio button (for selecting one of many choices)
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>Also note that the default width of a text input field is 20 characters.</p>
</body>
</html>
OUTPUT
<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 form-handler is typically a server page with a script for processing input data.
<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>
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?
However, when GET is used, the submitted form data will be visible in the page address field:
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.
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>
<!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>
<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>
Example
<option value="fiat" selected>Fiat</option>
The <textarea> Element
Example
<textarea name="message" rows="10" cols="30">
The cat was playing in the garden.
</textarea>
The <button> Element
Example
<button type="button" onclick="alert('Hello World!')">Click Me!</button>
Input Type Text
Example
<form>
First name:<br>
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
Input Type Password
Example
<form>
User name:<br>
<input type="text" name="username"><br>
User password:<br>
<input type="password" name="psw">
</form>
Input Type Submit
The form-handler is typically a server page with a script for processing input data.
<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
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
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
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.
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.
<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.
<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>©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>©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 (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.
There are number of events which are fired during various stages of the drag and drop operation. These events are
listed below −
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 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 −
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.
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>
#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>
return true;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</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>
</body>
</html>
This will produce the following result −
The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the
control −
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.
The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control
using JavaScript −
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).
<!DOCTYPE HTML>
<html>
<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 −
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
<!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 −
The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the
control −
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.
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.
Inline CSS
<html>
<body>
</body>
</html>
Internal CSS
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>
body {
background-color: powderblue;
}
h1 {
color: blue;
}
p {
color: red;
}
CSS Fonts
<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
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
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;
}
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;
}
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>
If you do not specify a border for the table, it will be displayed without borders.
Example
table, th, td {
border: 1px solid black;
}
Example
th {
text-align: left;
}
Example
table {
border-spacing: 5px;
}
Table properties
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>
<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>
<p>Hover over the div element below, to see the transition effect:</p>
<div></div>
</body>
</html>
Specify the Speed Curve of the Transition
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;
}
<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>
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>
</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;}
}
<!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>
The following example uses the value "infinite" to make the animation continue for ever:
animation-iteration-count: infinite;
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;
}
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.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript in Body</h2>
<p id="demo"></p>
<script>
</script>
</body>
</html>
OUTPUT
JavaScript Output
JavaScript Display Possibilities
Ex2:
<!DOCTYPE html>
<html>
<body>
<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>
<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:
Fixed values
Variable values
JavaScript Literals
The two most important syntax rules for fixed values are:
10.50
1001
Try it Yourself »
"John Doe"
'John Doe'
JavaScript Variables
let x;
x = 6;
</script>
<body onclick="disp()">
</body>
</html>
EX2:
<body onmouseover="disp()">
Inputs
Output
JavaScript DOM Model
VALIDATION
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
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.
1 constructor
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
1 Date()
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()
5 getHours()
6 getMilliseconds()
7 getMinutes()
8 getMonth()
9 getSeconds()
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()
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()
15 getUTCHours()
16 getUTCMilliseconds()
17 getUTCMinutes()
18 getUTCMonth()
19 getUTCSeconds()
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()
24 setMilliseconds()
25 setMinutes()
26 setMonth()
27 setSeconds()
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
1 MAX_VALUE
2 MIN_VALUE
3 NaN
4 NEGATIVE_INFINITY
5 POSITIVE_INFINITY
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.
1 toExponential()
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()
Boolean Properties
1 constructor
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
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()
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()
2 acos()
3 asin()
4 atan()
5 atan2()
6 ceil()
7 cos()
8 exp()
Returns EN, where N is the argument, and E is Euler's constant, the base of
the natural logarithm.
9 floor()
An array is a special variable, which can hold more than one value:
const cars = ["Saab", "Volvo", "BMW"];
Creating an 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";
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.
1 constructor
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
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.
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()
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()
7 lastIndexOf()
</script>
</body>
</html>
Output
Book title is : Perl
Book author is : Mohtashim
Book price is : 100
<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);
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.
Mouse events:
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
Form events:
Event Performed Event Handler Description
change onchange When the user modifies or changes the value of a form element
Window/Document events
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
<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">
</form>
</body>
</html>
<html>
<script>
function disp()
if(frm.gender.value=="")
else
document.writeln(frm.gender.value);
</script>
<body>
<form name="frm">
</form>
</body>
</html>
Combobox validation
<html>
<script>
function disp()
if(frm.branch.value=="None")
else
</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>
</form>
</body>
</html>
<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>
</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 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>
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
Ex:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
</div>
</body>
</html>
output
Example explained:
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.
<!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'">
</div>
</body>
</html>
Output
AngularJS Expressions
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 Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<br>
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>
</body>
</html>
AngularJS Controller
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
AngularJS Strings
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</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.
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
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
AngularJS Arrays
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</body>
</html>
Like JavaScript expressions, AngularJS expressions can contain literals, operators, and variables.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript expressions do.
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>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
FILTERS
AngularJS Filters
AngularJS Filters
Filters can be added to expressions by using the pipe character |, followed by a filter.
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>
</body>
</html>
Example
<div ng-app="myApp" ng-controller="personCtrl">
</div>
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>
<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>
</body>
</html>
DIRECTIVES IN DOM
AngularJS Directives
❮ PreviousNext ❯
AngularJS has a set of built-in directives which offers functionality to your applications.
AngularJS Directives
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
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.
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">
</div>
Try it Yourself »
Using ng-init is not very common. You will learn how to initialize data in the chapter about controllers.
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</div>
</body>
</html>
Normally, you will not use ng-init. You will use a controller or module instead.
The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
In addition to all the built-in AngularJS directives, you can create your own directives.
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>
Element name
Attribute
Class
Comment
<!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>
</body>
</html>
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
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>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>
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>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>
EXPRESSION
AngularJS Expressions
AngularJS Expressions
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
<!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>
</div>
<p>The background color of the input box will be whatever you write in the input field.</p>
</body>
</html>
AngularJS Numbers
Example
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
</body>
</html>
AngularJS Controllers
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.
In AngularJS, $scope is the application object (the owner of application variables and functions).
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.
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 »
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
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 available for both the view and the controller.
Example
<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}}.
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>
<input ng-model="name">
</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>
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";
});
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 ❯
Creating a Module
<div ng-app="myApp">...</div>
<script>
</script>
AngularJS 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.
API Description
angular.lowercase() Converts a string to lowercase
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>