100% found this document useful (2 votes)
155 views

HTML5 Elements: Web Technology Assignment - 1947234

HTML5 introduces several new form attributes to make forms more powerful and customizable. These include autofocus to focus on the first form field, autocomplete to turn form autofill on or off, novalidate to submit a form without validation, and form to associate orphaned form controls with a form. Microdata allows adding semantics to web pages through custom elements and properties represented by regular HTML elements using itemscope and itemprop attributes.

Uploaded by

Abhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
155 views

HTML5 Elements: Web Technology Assignment - 1947234

HTML5 introduces several new form attributes to make forms more powerful and customizable. These include autofocus to focus on the first form field, autocomplete to turn form autofill on or off, novalidate to submit a form without validation, and form to associate orphaned form controls with a form. Microdata allows adding semantics to web pages through custom elements and properties represented by regular HTML elements using itemscope and itemprop attributes.

Uploaded by

Abhi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

1.

HTML5 Elements

HTML5 elements are marked up using start tags and end tags. Tags are delimited
using angle brackets with the tag name in between. The difference between start tags
and end tags is that the latter includes a slash before the tag name. Following is the
example of an HTML5 element

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 1


2. HTML Attributes
HTML5 adds a number of new attributes and we have already seen many of them while
discussing the new input types. We will see a few more attributes in this section. These attributes
make the elements more useful.

autofocus
<!DOCTYPE html>
<html> attribute can be used to focus to an element when the page loads. It is a boolean
The autofocus
<head>
attribute, that is you do not have to set any value to this attribute.
<title>Autofocus Example</title>
Sample<html>
Code:
</head>
<body>
<form action="#">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
<input type="submit">
</form>
</body>
</html>

autocomplete

The autocomplete attribute can be used to on or off the autocomplete feature of form input
elements and <form> element. If autocomplete is on, browser automatically completes
values based on the previous entries. This attribute works with <form> as well as with
input types text, email, url, tel, password, text, range, date and color. By making
autocomplete on for the <form>, all the input fields will have autocomplete on. Even the
autocomplete is on for <form>, you can make it off for any of the input fields if you want.
Sample Code:
<!DOCTYPE html>
<html> <head>
<title>Autocomplete Example</title>
</head>
<body>
<form action="#" autocomplete="on">
First name:<input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
Password: <input type="password" name="password" autocomplete="off"><br>
E-mail: <input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>
WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 2
novalidate
The novalidate attribute can be used with <form> element if you do not want the form data
to be validated when submitted.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>Novalidate Example</title>
</head>
<body>
<form action="#" novalidate>
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email"><br>
<input type="submit">
</form>
</body>
</html>

form
The form attribute can be used to associate any orphaned form control with any <form> on
the page. You can specify one or more forms an input element belongs to. You just have to
specify the form ids separated using whitespace.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action="#" id="myform">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
<input type="submit">
</form>
<p>Though the form ends here, the email field is also part of this form!!!</p>
Email: <input type="email" name="email" form="myform">
</body>
</html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 3


formaction
The formaction attribute can be used to override the action attribute of the <form> element
and to specify the URL of a file that will process the input control when the form is
submitted. You can use formaction attribute with input types submit and image.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>FormAction Example</title>
</head>
<body>
<form action="http://abctest.com/process.php" id="myform">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" formaction="http://xyz.com/admincheck.asp">
</form>
</body>
</html>

formmethod
The formmethod attribute can be used to override the method attribute of the <form>
element and to specify the HTTP method for sending form data to the action URL when the
form is submitted. You can use formmethod attribute with input types submit and image.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>FormMethod Example</title>
</head>
<body>
<form action="http://abctest.com/process.php" method="get">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" formmethod="post">
</form>
</body>
</html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 4


formenctype
The formenctype attribute can be used to override the enctype attribute of the <form>
element and to specify how the form data should be encoded when submitting to the
server using POST method. You can use this attribute with input types submit and image.
The value you can set to this attribute is application/x-www-form-urlencoded (default),
multipart/form-data (no encoding) or text/plain.
Sample Code:-
<!DOCTYPE html>
<html>
<head>
<title>FormEnctype Example</title>
</head>
<body>
<form action="#" enctype="text/plain">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email"><br>
<input type="submit" formenctype="application/x-www-form-urlencoded">
</form>
</body>
</html>
formnovalidate
The formnovalidate attribute can be used to override the novalidate attribute of the <form>
element. You can use formnovalidate attribute with input type submit.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>FormNoValidate Example</title>
</head>
<body>
<form action="#">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email"><br>
<input type="submit" formnovalidate>
</form>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 5


</body>
</html>
formtarget
The formtarget attribute can be used to override the target attribute of the <form> element
and to specify where to display the form response. You can use formtarget attribute with
input types submit and image. The value you can set to this attribute is _blank, _self,
_parent or _top.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>FormTarget Example</title>
</head>
<body>
<form action="#">
First name:<input type="text" name="fname" autofocus><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email"><br>
<input type="submit" formtarget="_blank">
</form>
</body>
</html>
height and width
You can use the height and width attributes to specify the height and width of an <input>
element and these attributes are only used with input type image.
Sample Code
<!DOCTYPE html>
<html>
<head>
<title>Height and Width</title>
</head>
<body>
<form action="#" enctype="text/plain">
<input type="image" src="baby.jpg" alt="baby" width="200" height="200"><br />
<input type="submit">
</form>
</body>
</html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 6


multiple
You can use the multiple attribute if you want to allow the user to enter more than one
value in the input field. It is a boolean attribute and can be used with email and file input
types.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>Multiple Attribute</title>
</head>
<body>
<form action="#">
First name:<input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
E-mail: <input type="email" name="email" size="35" multiple><br>
<input type="submit">
</form>
</body>
</html>
placeholder
You can use the placeholder attribute if you want to add a hint that describes the expected
value of an input field. You can use this attribute with text, search, email, url, password
and tel input types.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>Placeholder Attribute</title>
</head>
<body>
<form action="#">
<input type="text" name="fname" placeholder="First name:"><br />
<input type="text" name="lname" placeholder="Last name:"><br />
<input type="submit">
</form>
</body>
</html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 7


3. Microdata
Microdata is a standardized way to provide additional semantics in your web pages.

Microdata lets you define your own customized elements and start embedding custom
properties in your web pages. At a high level, microdata consists of a group of name-value
pairs.

The groups are called items, and each name-value pair is a property. Items and properties
are represented by regular elements.

Example
 To create an item, the itemscope attribute is used.

 To add a property to an item, the itemprop attribute is used on one of the item's
descendants.

Here there are two items, each of which has the property "name" −

<html>

<body>

<div itemscope>

<p>My name is <span itemprop = "name">Zara</span>.</p>

</div>

<div itemscope>

<p>My name is <span itemprop = "name">Nuha</span>.</p>

</div>

</body>

</html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 8


Global Attributes
Microdata introduces five global attributes which would be available for any element to
use and give context for machines about your data.

Sr.No. Attribute & Description

itemscope
1 This is used to create an item. The itemscope attribute is a Boolean
attribute that tells that there is Microdata on this page, and this is
where it starts.

itemtype
2
This attribute is a valid URL which defines the item and provides
the context for the properties.

itemid
3
This attribute is global identifier for the item.

itemprop
4
This attribute defines a property of the item.

itemref
5
This attribute gives a list of additional elements to crawl to find
the name-value pairs of the item.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 9


Properties Datatypes
Properties generally have values that are strings as mentioned in above example but they
can also have values that are URLs. Following example has one property, "image", whose
value is a URL −

<div itemscope>

<img itemprop = "image" src = "tp-logo.gif" alt = "TutorialsPoint">

</div>

Properties can also have values that are dates, times, or dates and times. This is achieved
using the time element and its datetime attribute.

<html>

<body>

<div itemscope>

My birthday is:

<time itemprop = "birthday" datetime = "1971-05-08">

Aug 5th 1971

</time>

</div>

</body>

</html>

Properties can also themselves be groups of name-value pairs, by putting the itemscope
attribute on the element that declares the property.

Microdata API support


If a browser supports the HTML5 microdata API, there will be a getItems() function on the
global document object. If browser doesn't support microdata, the getItems() function will
be undefined.
WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 10
function supports_microdata_api() {

return !!document.getItems;

Modernizr does not yet support checking for the microdata API, so you’ll need to use the
function like the one listed above.

The HTML5 microdata standard includes both HTML markup (primarily for search
engines) and a set of DOM functions (primarily for browsers).

You can include microdata markup in your web pages, and search engines that don't
understand the microdata attributes will just ignore them. But if you need to access or
manipulate microdata through the DOM, you'll need to check whether the browser
supports the microdata DOM API.

Defining Microdata Vocabulary


To define microdata vocabulary you need a namespace URL which points to a working
web page. For example https://data-vocabulary.org/Person can be used as the
namespace for a personal microdata vocabulary with the following named properties −

 name − Person name as a simple string

 Photo − A URL to a picture of the person.

 URL − A website belonging to the person.

Using about properties a person microdata could be as follows −

<html>

<body>

<div itemscope>

<section itemscope itemtype = "http://data-vocabulary.org/Person">

<h1 itemprop = "name">Gopal K Varma</h1>

<p>

<img itemprop = "photo"

src = "http://www.tutorialspoint.com/green/images/logo.png">

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 11


</p>

<a itemprop = "url" href = "#">Site</a>

</section>

</div>

</body>

</html>

5. ARIA Accessible
Accessible Rich Internet Applications (ARIA) is a set of attributes that define ways to make
web content and web applications (especially those developed with JavaScript) more
accessible to people with disabilities.
It supplements HTML so that interactions and widgets commonly used in applications can
be passed to assistive technologies when there is not otherwise a mechanism. For example,
ARIA enables accessible navigation landmarks in HTML4, JavaScript widgets, form hints
and error messages, live content updates, and more.

ne way we can use ARIA is by adding it to our HTML. You may already be familiar with
semantic elements in HTML such as nav, button or header. It’s quite easy to see what these
elements would be used for. These elements give more meaning to the content of a page,
and we can use a combination of these elements and ARIA in our markup. However, there
are a few things to keep in mind when using them together.

ARIA Roles

ARIA roles are added to HTML markup like an attribute. They define the type of element
and suggest what purpose it serves. The following example identifies the element as some
kind of banner:

<header role="banner">

The following example, often placed in a containing element, suggests that its content
provides some information about the content within the containing element:

<div role="contentinfo">

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 12


This website was built by Georgie.

</div>

An alert with dynamic content should use role="alert":

<div role="alert">

</div>

This one is my personal favorite, which is used when an element is simply for presentation.
If you imagine someone using a screen reader, think of the elements that they would not
want read out. One example is an element that might contain a visual decoration, or is an
empty element simply serving an image or background color.

<a href="aria.html" role="presentation">

<img src="aria-thumbnail.jpg" role="presentation" alt="Use ARIA effectively">

</a>

ARIA Attributes

ARIA attributes are slightly different from roles. They are added to markup in the same
way, but there is a range of ARIA attributes available for use. All ARIA attributes are
prefixed with aria-. There are two types of attributes, states and properties.

 The value of states is bound to change as a result of user interaction.


 The value of properties is less likely to change.

An example of an ARIA attribute that is a state is aria-checked. This is used to show the state
of elements that are emulating interactive elements, such as checkboxes and radio buttons,
but are not the native elements themselves (e.g. custom UI elements built
with div and span tags).

<span role="checkbox"

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 13


aria-checked="true"

tabindex="0"

id="simulatedcheckbox">

</span>

An example of an ARIA attribute that is a property is aria-label. This is used when a label for
a form element is not visible on the page (perhaps because it makes no sense to make it
visible, or if the design dictates this). For cases when label text is visible, aria-labelledby is the
more appropriate attribute to use.

This can be done with the figure element as shown below.

<figure aria-labelledby="operahouse_1" role="group">

<img src="operahousesteps.jpg" alt="The Sydney Opera House">

<figcaption id="operahouse_1">We saw the opera <cite>Barber of Seville</cite>


here!</figcaption>

</figure>

You can read more about supported states and properties on the W3C website.

Rules of ARIA

Before you get too keen, remember that we don’t want to be adding ARIA to every
element, for a couple of reasons.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 14


6. Web Forms 2.0
Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and
attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free
us from a great deal of tedious scripting and styling that was required in HTML4.

he <input> element in HTML4


HTML4 input elements use the type attribute to specify the data type.HTML4 provides
following types −

Sr.No. Type & Description

1 text

A free-form text field, nominally free of line breaks.

password
2
A free-form text field for sensitive information,
nominally free of line breaks.

checkbox
3
A set of zero or more values from a predefined list.

radio
4
An enumerated value.

submit
5
A free form of button initiates form submission.

file
6
An arbitrary file with a MIME type and optionally a
file name.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 15


image

7 A coordinate, relative to a particular image's size, with


the extra semantic that it must be the last value
selected and initiates form submission.

hidden
8
An arbitrary string that is not normally displayed to
the user.

select
9
An enumerated value, much like the radio type.

textarea
10
A free-form text field, nominally with no line break
restrictions.

button
11
A free form of button which can initiates any event
related to button.

Following is the simple example of using labels, radio buttons, and submit buttons −

<form action = "http://example.com/cgiscript.pl" method = "post">

<p>

<label for = "firstname">first name: </label>

<input type = "text" id = "firstname"><br />

<label for = "lastname">last name: </label>

<input type = "text" id = "lastname"><br />

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 16


<label for = "email">email: </label>

<input type = "text" id = "email"><br>

<input type = "radio" name = "sex" value = "male"> Male<br>

<input type = "radio" name = "sex" value = "female"> Female<br>

<input type = "submit" value = "send"> <input type = "reset">

</p>

</form>

The <input> element in HTML5


Apart from the above-mentioned attributes, HTML5 input elements introduced several
new values for the type attribute. These are listed below.

NOTE − Try all the following example using latest version of Opera browser.

Sr.No. Type & Description

datetime

1 A date and time (year, month, day, hour, minute,


second, fractions of a second) encoded according to
ISO 8601 with the time zone set to UTC.

datetime-local

2 A date and time (year, month, day, hour, minute,


second, fractions of a second) encoded according to
ISO 8601, with no time zone information.

date
3
A date (year, month, day) encoded according to ISO
8601.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 17


month
4
A date consisting of a year and a month encoded
according to ISO 8601.

week
5
A date consisting of a year and a week number
encoded according to ISO 8601.

time
6
A time (hour, minute, seconds, fractional seconds)
encoded according to ISO 8601.

number
7
It accepts only numerical value. The step attribute
specifies the precision, defaulting to 1.

range
8
The range type is used for input fields that should
contain a value from a range of numbers.

email

It accepts only email value. This type is used for input


9
fields that should contain an e-mail address. If you try
to submit a simple text, it forces to enter only email
address in email@example.com format.

url

10 It accepts only URL value. This type is used for input


fields that should contain a URL address. If you try to
submit a simple text, it forces to enter only URL
address either in http://www.example.com format or

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 18


in http://example.com format.

The <output> element


HTML5 introduced a new element <output> which is used to represent the result of
different types of output, such as output written by a script.

You can use the for attribute to specify a relationship between the output element and
other elements in the document that affected the calculation (for example, as inputs or
parameters). The value of the for attribute is a space-separated list of IDs of other
elements.

<!DOCTYPE HTML>

<html>

<head>

<script type = "text/javascript">

function showResult() {

x = document.forms["myform"]["newinput"].value;

document.forms["myform"]["result"].value = x;

</script>

</head>

<body>

<form action = "/cgi-bin/html5.cgi" method = "get" name = "myform">

Enter a value : <input type = "text" name = "newinput" />

<input type = "button" value = "Result" onclick = "showResult();" />

<output name = "result"></output>

</form>

</body>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 19


</html>

The placeholder attribute


HTML5 introduced a new attribute called placeholder. This attribute on <input> and
<textarea> elements provide a hint to the user of what can be entered in the field. The
placeholder text must not contain carriage returns or line-feeds.

Here is the simple syntax for placeholder attribute −

<input type = "text" name = "search" placeholder = "search the web"/>

This attribute is supported by latest versions of Mozilla, Safari and Crome browsers only.

<!DOCTYPE HTML><html>

<body>

<form action = "/cgi-bin/html5.cgi" method = "get">

Enter email : <input type = "email" name = "newinput"

placeholder = "email@example.com"/>

<input type = "submit" value = "submit" />

</form>

</body>

</html

The autofocus attribute


This is a simple one-step pattern, easily programmed in JavaScript at the time of
document load, automatically focus one particular form field.

HTML5 introduced a new attribute called autofocus which would be used as follows −

<input type = "text" name = "search" autofocus/>

This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only.

<!DOCTYPE HTML>

<html><body>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 20


<form action = "/cgi-bin/html5.cgi" method = "get">

Enter email : <input type = "text" name = "newinput" autofocus/>

<p>Try to submit using Submit button</p>

<input type = "submit" value = "submit" />

</form>

</body>

</html>

7. Multimedia

HTML5 has introduced two new multimedia tags, AUDIO and VIDEO, for displaying the
audio and video streams on a Web page.

You can play the multimedia files, which are stored in your local computer, on the Web
page by specifying their location. The src attribute is used to specify the multimedia file to
play it on the Web page.

If the Web browser does not support AUDIO and VIDEO tags, then the text defined
between the starting and the closing tags of these tags are displayed on the Web page.

Attributes of AUDIO Tag

The AUDIO tag of HTML5 supports only three audio file formats i.e. .oog, .mp3, .wav

Following table shows the attributes of the AUDIO tag

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 21


Attribute Description

autoplay Plays the audio file as soon as the Web page loads

controls Displays the controls on the Web page, such as play and pause buttons

loop Replays the audio file

preload Specifies whether the audio file is preloaded on the Web page or not

src Provides the location of the audio file to play

Attributes of VIDEO Tag

You can use the VIDEO tag to display a video file on the Web page. The VIDEO tag
supports the .gov and .mp4 file formats.

Following table describes attributes of the VIDEO tag

Attribute Description

audio Controls the default state of the video's audio channel

autoplay Plays the audio file as soon as the Web page loads

controls Displays the controls on a Web page, such as play and pause buttons

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 22


height Specifies the height of the VIDEO tag

loop Replays the video file

preload Specifies whether the video file is preloaded on the Web page or not

poster Provides an image to be displayed when the video file is not available

src Provides the location of the video file to play

width Specifies the width of the VIDEO tag

You can also use the SOURCE tag within the opening and the closing tags of the VIDEO
tag to provide the source of the video file.

The SOURCE tag is used in a situation when the location of the video file is not confirmed.
In this case, the VIDEO tag plays the first video file located in the specified path. The
following code snippet shows the use of the VIDEO tag :

<VIDEO src="video.ogv" autoplay="true" loop="3" controls>


</VIDEO>

In the above code snippet, we have defined a video.ogv file in the src attribute. We have
also set the autoplay attribute to true, which implies that the video file start playing as soon
as the Web page loads. the loop attribute is set to 3, which implies that the video file will be
played three times. In addition, the controls attribute displays the controls on the video
player.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 23


HTML Audio

An audio file is used to store audio data on various data, such as a computer system,
mp3 players, and mobile phones. To store an audio data, you need to convert it into a
digital format. The process of converting audio data into a digital file is called encoding
of the raw audio data. It involves taking samples of audio data and storing them in a
compressed format to reduce the file size.

An audio player decodes these compressed sample files to make the audio waves
audible. The process of converting a digital file into the audio data is known as
decoding. A codec is performs the encoding and decoding of the raw audio data.

List of Commonly Used Audio File Formats

The table given below lists commonly used audio file formats:

File
Format Description
Extension

MIDI (Musical Instrument Digital Interface). Main format for


all electronic music devices like synthesizers and PC sound
.mid
MIDI cards. MIDI files do not contain sound, but digital notes that
.midi
can be played by electronics. Plays well on all computers and
music hardware, but not in web browsers

WMA (Windows Media Audio). Developed by Microsoft.


WMA .wma Commonly used in music players. Plays well on Windows
computers, but not in web browsers

.rm RealAudio. Developed by Real Media to allow streaming of


RealAudio
.ram audio with low bandwidths. Does not play in web browsers

WAV .wav WAV. Developed by IBM and Microsoft. Plays well on


Windows, Macintosh, and Linux operating systems.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 24


Supported by HTML5

AAC (Advanced Audio Coding). Developed by Apple as the


AAC .aac default format for iTunes. Plays well on Apple computers, but
not in web browsers

MP3 files are actually the sound part of MPEG files. MP3 is the
most popular format for music players. Combines good
MP3 .mp3
compression (small files) with high quality. Supported by all
browsers

Ogg. Developed by the Xiph.Org Foundation. Supported by


Ogg .ogg
HTML5

MP4 is a video format, but can also be used for audio. MP4
MP4 .mp4 video is the upcoming video format on the internet. This leads
to automatic support for MP4 audio by all browsers

HTML <audio> tag

To play an audio file in HTML, use the <audio> tag.

Let's look at the following example, to know how to embed audio files into your web
page.

<audio controls>
<source src="songs.ogg" type="audio/ogg">
<source src="songs.mp3" type="audio/mpeg">
Your browser does not support the audio tag.
</audio>

HTML Audio Working

The controls attribute adds audio controls, like play, pause, and volume.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 25


Text between the <audio> and </audio> tags will display in browsers that do not
support the <audio> tag.

Multiple <source> tags can link to different audio files. The browser will use the first
recognized format.

HTML Video

A video file is a collection of images that is displayed in a sequence representing scenes


in motion. Similar to the audio file system, video files are also encoded or decoded
using the various video codecs, such as DivX and QuickTime.

List of Commonly Used Video File Formats

The table given below lists commonly used video file formats.

Format File Description

MPEG. Developed by the Moving Pictures Expert Group. The first popular
.mpg
MPEG video format on the web. Used to be supported by all browsers, but it is not
.mpeg
supported in HTML5 (See MP4)

MP4. Developed by the Moving Pictures Expert Group. Based on QuickTime.


MPEG-4
.mp4 Commonly used in newer video cameras and TV hardware. Supported by all
or MP4
HTML5 browsers. Recommended by YouTube

AVI (Audio Video Interleave). Developed by Microsoft. Commonly used in


AVI .avi video cameras and TV hardware. Plays well on Windows computers, but not
in web browsers

QuickTime. Developed by Apple. Commonly used in video cameras and TV


QuickTime .mov hardware. Plays well on Apple computers, but not in web browsers. (See
MP4)

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 26


.swf Flash. Developed by Macromedia. Often requires an extra component (plug-
Flash
.flv in) to play in web browsers

RealVideo. Developed by Real Media to allow video streaming with low


.rm
RealVideo bandwidths. It is still used for online video and Internet TV, but does not play
.ram
in web browsers

WMV (Windows Media Video). Developed by Microsoft. Commonly used in


WMV .wmv video cameras and TV hardware. Plays well on Windows computers, but not
in web browsers

WebM. Developed by the web giants, Mozilla, Opera, Adobe, and Google.
WebM .webm
Supported by HTML5

Ogg .ogg Theora Ogg. Developed by the Xiph.Org Foundation. Supported by HTML5

HTML <video> tag

To show a video in HTML, use the <video> tag. Let's look at the following example, to
know how to embed video into your webpage.

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


<source src="song.mp4" type="video/mp4">
<source src="song.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

HTML Video Working

The controls attribute adds video controls, like play, pause, and volume.

It is a good idea to always include width and height attributes. If height and width are
not set, the browser does not know the size of the video. The effect will be that the page
will change (or flicker) while the video loads.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 27


Text between the <video> and </video> tags will only display in browsers that do not
support the <video> tag.

Multiple <source> tags can link to different video files. The browser will use the first
recognized format.

HTML <video> Autoplay

To start a video automatically use the autoplay attribute.

Let's look at the following example, to know hot to embed video and set to autoplay
when web page loads.

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


<source src="songs.mp4" type="video/mp4">
<source src="songs.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

8. Drawing support
Another new element in HTML5 is the <canvas> tag. It’s just what it sounds like——a
blank surface for drawing. You need to use JavaScript to manipulate and draw on the
canvas.
You may want to give your canvas element an id attribute so you can programmatically
access it from your JavaScript code (or if you’re using jQuery and it’s the only canvas on
the page, you could access it using $(‘canvas’) without needing to name it).
You can also (optionally) specify a height and a width for the canvas. Between the
<canvas> and </canvas>, you can specify some text to display in browsers that don’t
support the canvas element.
Here is a simple example of using the canvas to draw. (I’m attempting to draw the flag
of Scotland. Please forgive any inaccuracies.)
<!DOCTYPE HTML>
<html>
<body>
<canvas id="myCanvas">Your browser does not support the canvas tag.</canvas>
<script type="text/javascript">

var canvas = document.getElementById('myCanvas');

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 28


var ctx = canvas.getContext('2d');

// Draw blue rectangle


ctx.fillStyle = '#0065BD';
ctx.fillRect(0, 0, 125, 75);

// Draw white X
ctx.beginPath();
ctx.lineWidth = "15";
ctx.strokeStyle = "white";
ctx.moveTo(0, 0);
ctx.lineTo(125, 75);
ctx.moveTo(125, 0);
ctx.lineTo(0, 75);
ctx.stroke();

</script>
</body>
</html>

What is SVG?

 SVG stands for Scalable Vector Graphics


 SVG is used to define graphics for the Web
 SVG is a W3C recommendation

The HTML <svg> Element

The HTML <svg> element is a container for SVG graphics.

SVG has several methods for drawing paths, boxes, circles, text, and graphic images.

<!DOCTYPE html>
<html>
<body>

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


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

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 29


</svg>

</body>
</html

9. Geolocation

HTML5 Geolocation API lets you share your location with your favorite web sites. A
JavaScript can capture your latitude and longitude and can be sent to backend web
server and do fancy location-aware things like finding local businesses or showing
your location on a map.

Today most of the browsers and mobile devices support Geolocation API. The
geolocation APIs work with a new property of the global navigator object ie.
Geolocation object which can be created as follows −

var geolocation = navigator.geolocation;

The geolocation object is a service object that allows widgets to retrieve information
about the geographic location of the device.

Geolocation Methods
The geolocation object provides the following methods −

Sr.No. Method & Description

getCurrentPosition()
1

This method retrieves the current geographic location of the user.

watchPosition()

2
This method retrieves periodic updates about the current geographic location of the
device.

clearWatch()
3
This method cancels an ongoing watchPosition call.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 30


Example
Following is a sample code to use any of the above method −

function getLocation() {

var geolocation = navigator.geolocation;

geolocation.getCurrentPosition(showLocation, errorHandler);

Here showLocation and errorHandler are callback methods which would be used to
get actual position as explained in next section and to handle errors if there is any.

Location Properties
Geolocation methods getCurrentPosition() and getPositionUsingMethodName()
specify the callback method that retrieves the location information. These methods are
called asynchronously with an object Position which stores the complete location
information.

The Position object specifies the current geographic location of the device. The location
is expressed as a set of geographic coordinates together with information about
heading and speed.

The following table describes the properties of the Position object. For the optional
properties if the system cannot provide a value, the value of the property is set to null.

Property Type Description

Specifies the geographic location of the device. The


coords objects location is expressed as a set of geographic coordinates
together with information about heading and speed.

Specifies the latitude estimate in decimal degrees. The


coords.latitude Number
value range is [-90.00, +90.00].

Specifies the longitude estimate in decimal degrees. The


coords.longitude Number
value range is [-180.00, +180.00].

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 31


[Optional] Specifies the altitude estimate in meters
coords.altitude Number
above the WGS 84 ellipsoid.

[Optional] Specifies the accuracy of the latitude and


coords.accuracy Number
longitude estimates in meters.

[Optional] Specifies the accuracy of the altitude estimate


coords.altitudeAccuracy Number
in meters.

[Optional] Specifies the device's current direction of


coords.heading Number movement in degrees counting clockwise relative to true
north.

[Optional] Specifies the device's current ground speed in


coords.speed Number
meters per second.

Specifies the time when the location information was


timestamp date
retrieved and the Position object created.

Example
Following is a sample code which makes use of Position object. Here showLocation
method is a callback method −

function showLocation( position ) {

var latitude = position.coords.latitude;

var longitude = position.coords.longitude;

...

Handling Errors
Geolocation is complicated, and it is very much required to catch any error and handle
it gracefully.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 32


The geolocations methods getCurrentPosition() and watchPosition() make use of an
error handler callback method which gives PositionError object. This object has
following two properties −

Property Type Description

code Number Contains a numeric code for the error.

message String Contains a human-readable description of the error.

The following table describes the possible error codes returned in the PositionError
object.

Code Constant Description

The method failed to retrieve the location of the device


0 UNKNOWN_ERROR
due to an unknown error.

The method failed to retrieve the location of the device


1 PERMISSION_DENIED because the application does not have permission to
use the Location Service.

2 POSITION_UNAVAILABLE The location of the device could not be determined.

The method was unable to retrieve the location


3 TIMEOUT information within the specified maximum timeout
interval.

Example
Following is a sample code which makes use of PositionError object. Here
errorHandler method is a callback method −

function errorHandler( err ) {

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 33


if (err.code == 1) {

// access is denied

...

Position Options
Following is the actual syntax of getCurrentPosition() method −

getCurrentPosition(callback, ErrorCallback, options)

Here third argument is the PositionOptions object which specifies a set of options for
retrieving the geographic location of the device.

Following are the options which can be specified as third argument −

Property Type Description

Specifies whether the widget wants to receive the most


enableHighAccuracy Boolean
accurate location estimate possible. By default this is false.

The timeout property is the number of milliseconds your


timeout Number
web application is willing to wait for a position.

Specifies the expiry time in milliseconds for cached location


maximumAge Number
information.

Example
Following is a sample code which shows how to use above mentioned methods −

function getLocation() {

var geolocation = navigator.geolocation;

geolocation.getCurrentPosition(showLocation, errorHandler, {maximumAge: 75000});

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 34


10. WebSockets

WebSockets is a next-generation bidirectional communication technology for web


applications which operates over a single socket and is exposed via a JavaScript
interface in HTML 5 compliant browsers.

Once you get a Web Socket connection with the web server, you can send data from
browser to server by calling a send method, and receive data from server to browser by
an onmessage event handler.

Following is the API which creates a new WebSocket object.

var Socket = new WebSocket(url, [protocal] );

Here first argument, url, specifies the URL to which to connect. The second attribute,
protocol is optional, and if present, specifies a sub-protocol that the server must support
for the connection to be successful.

WebSocket Attributes

Following are the attribute of WebSocket object. Assuming we created Socket object as
mentioned above −

Sr.No. Attribute & Description

Socket.readyState

The readonly attribute readyState represents the state of the connection. It can
have the following values −

1  A value of 0 indicates that the connection has not yet been established.
 A value of 1 indicates that the connection is established and
communication is possible.
 A value of 2 indicates that the connection is going through the closing
handshake.
 A value of 3 indicates that the connection has been closed or could not

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 35


be opened.

Socket.bufferedAmount
2
The readonly attribute bufferedAmount represents the number of bytes of
UTF-8 text that have been queued using send method.

WebSocket Events

Following are the events associated with WebSocket object. Assuming we created
Socket object as mentioned above −

Event Event Handler Description

open Socket.onopen This event occurs when socket connection is


established.

message Socket.onmessage This event occurs when client receives data from
server.

error Socket.onerror This event occurs when there is any error in


communication.

close Socket.onclose This event occurs when connection is closed.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 36


WebSocket Methods

Following are the methods associated with WebSocket object. Assuming we created
Socket object as mentioned above −

Sr.No. Method & Description

Socket.send

1 The senddatadata method transmits data using the connection.

Socket.close
2
The close method would be used to terminate any existing connection.

WebSocket Example

A WebSocket is a standard bidirectional TCP socket between the client and the server.
The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a
HTTP handshake. After the handshake, either side can send data.

Client Side HTML & JavaScript Code

At the time of writing this tutorial, there are only few web browsers supporting
WebSocketinterface. You can try following example with latest version of Chrome,
Mozilla, Opera and Safari.

<!DOCTYPE HTML>

<html>
<head>

<script type = "text/javascript">


function WebSocketTest() {

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 37


if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");

// Let us open a web socket


var ws = new WebSocket("ws://localhost:9998/echo");

ws.onopen = function() {

// Web Socket is connected, send data using send()


ws.send("Message to send");
alert("Message is sent...");
};

ws.onmessage = function (evt) {


var received_msg = evt.data;
alert("Message is received...");
};

ws.onclose = function() {

// websocket is closed.
alert("Connection is closed...");
};
} else {

// The browser doesn't support WebSocket


alert("WebSocket NOT supported by your Browser!");
}

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 38


}
</script>
</head>
<body>
<div id = "sse">
<a href = "javascript:WebSocketTest()">Run WebSocket</a>
</div>

</body>
</html>

11. Web Workers


JavaScript was designed to run in a single-threaded environment, meaning multiple
scripts cannot run at the same time. Consider a situation where you need to handle UI
events, query and process large amounts of API data, and manipulate the DOM.

JavaScript will hang your browser in situation where CPU utilization is high. Let us
take a simple example where JavaScript goes through a big loop −

<!DOCTYPE HTML>

<html>

<head>

<title>Big for loop</title>

<script>

function bigLoop() {

for (var i = 0; i <= 10000; i += 1) {

var j = i;

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 39


alert("Completed " + j + "iterations" );

function sayHello(){

alert("Hello sir...." );

</script>

</head>

<body>

<input type = "button" onclick = "bigLoop();" value = "Big Loop" />

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

</body>

</html>

Web Storage
HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing
structured data on the client side and to overcome following drawbacks.

 Cookies are included with every HTTP request, thereby slowing down your web
application by transmitting the same data.

 Cookies are included with every HTTP request, thereby sending data unencrypted over the
internet.

 Cookies are limited to about 4 KB of data. Not enough to store required data.

The two storages are session storage and local storage and they would be used to
handle different situations.

The latest versions of pretty much every browser supports HTML5 Storage including
Internet Explorer.

Session Storage
The Session Storage is designed for scenarios where the user is carrying out a single
transaction, but could be carrying out multiple transactions in different windows at the
same time.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 40


HTML5 introduces the sessionStorage attribute which would be used by the sites to add
data to the session storage, and it will be accessible to any page from the same site
opened in that window, i.e., session and as soon as you close the window, the session
would be lost.

Following is the code which would set a session variable and access that variable −

<!DOCTYPE HTML>

<html>

<body>

<script type = "text/javascript">

if( sessionStorage.hits ) {

sessionStorage.hits = Number(sessionStorage.hits) +1;

} else {

sessionStorage.hits = 1;

document.write("Total Hits :" + sessionStorage.hits );

</script

<p>Refresh the page to increase number of hits.</p>

<p>Close the window and open it again and check the result.</p>

</body>

</html>

Local Storage
The Local Storage is designed for storage that spans multiple windows, and lasts
beyond the current session. In particular, Web applications may wish to store
megabytes of user data, such as entire user-authored documents or a user's mailbox,
on the client side for performance reasons.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 41


Again, cookies do not handle this case well, because they are transmitted with every
request.

ollowing is the code which would set a local storage variable and access that variable
every time this page is accessed, even next time, when you open the window −

<!DOCTYPE HTML>

<html>

<body>

<script type = "text/javascript">

if( localStorage.hits ) {

localStorage.hits = Number(localStorage.hits) +1;

} else {

localStorage.hits = 1;

document.write("Total Hits :" + localStorage.hits );

</script>

<p>Refresh the page to increase number of hits.</p>

<p>Close the window and open it again and check the result.</p

</body>

</html>

Delete Web Storage


Storing sensitive data on local machine could be dangerous and could leave a security
hole.

The Session Storage Data would be deleted by the browsers immediately after the
session gets terminated.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 42


To clear a local storage setting you would need to call localStorage.remove('key');
where 'key' is the key of the value you want to remove. If you want to clear all settings,
you need to call localStorage.clear() method.

Following is the code which would clear complete local storage −

<!DOCTYPE HTML>

<html>

<body>

<script type = "text/javascript">

localStorage.clear();

// Reset number of hits.

if( localStorage.hits ) {

localStorage.hits = Number(localStorage.hits) +1;

} else {

localStorage.hits = 1;

document.write("Total Hits :" + localStorage.hits );

</script>

<p>Refreshing the page would not to increase hit counter.</p>

<p>Close the window and open it again and check the result.</p>

</body>

</html>

12. Modernizr

Modernizr is a small JavaScript Library that detects the availability of native


implementations for next-generation web technologies

There are several new features which are being introduced through HTML5 and CSS3
but same time many browsers do not support these news features.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 43


Modernizr provides an easy way to detect any new feature so that you can take
corresponding action. For example, if a browser does not support video feature then
you would like to display a simple page.

You can create CSS rules based on the feature availability and these rules would apply
automatically on the webpage if browser does not support a new feature.

You can download latest version of this utility from Modernizr Download.

Syntax

Before you start using Modernizr, you would have to include its javascript library in
your HTML page header as follows −

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

As mentioned above, you can create CSS rules based on the feature availability and
these rules would apply automatically on the webpage if browser does not support a
new featur.

Following is the simple syntax to handle supported and non supported features −

/* In your CSS: */
.no-audio #music {
display: none; /* Don't show Audio options */
}
.audio #music button {
/* Style the Play and Pause buttons nicely */
}

<!-- In your HTML: -->


<div id="music">

<audio>
<source src="audio.ogg" />
<source src="audio.mp3" />

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 44


</audio>

<button id="play">Play</button>
<button id="pause">Pause</button>
</div>

Here it is notable that you need to prefix "no-" to every feature/property you want to
handle for the browser which does not support them.

Following is the syntax to detect a particular feature through Javascript −

if (Modernizr.audio) {
/* properties for browsers that
support audio */
}

else{
/* properties for browsers that
does not support audio */
}

Features detected by Modernizr

Following is the list of features which can be detected by Modernizr −

Feature CSS Property JavaScript Check

@font-face .fontface Modernizr.fontface

Canvas .canvas Modernizr.canvas

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 45


Canvas Text .canvastext Modernizr.canvastext

HTML5 Audio .audio Modernizr.audio

HTML5 Audio NA Modernizr.audio[format]


formats

HTML5 Video .video Modernizr.video

HTML5 Video NA Modernizr.video[format]


Formats

rgba .rgba Modernizr.rgba

hsla .hsla Modernizr.hsla

border-image .borderimage Modernizr.borderimage

border-radius .borderradius Modernizr.borderradius

box-shadow .boxshadow Modernizr.boxshadow

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 46


Multiple .multiplebgs Modernizr.multiplebgs
backgrounds

opacity .opacity Modernizr.opacity

CSS Animations .cssanimations Modernizr.cssanimations

CSS Columns .csscolumns Modernizr.csscolumns

CSS Gradients .cssgradients Modernizr.cssgradients

CSS Reflections .cssreflections Modernizr.cssreflections

CSS 2D Transforms .csstransforms Modernizr.csstransforms

CSS 3D Transforms .csstransforms3d Modernizr.csstransforms3d

CSS Transitions .csstransitions Modernizr.csstransitions

Geolocation API .geolocation Modernizr.geolocation

Input Types NA Modernizr.inputtypes[type]

Input Attributes NA Modernizr.input[attribute]

localStorage .localstorage Modernizr.localstorage

sessionStorage .sessionstorage Modernizr.sessionstorage

Web Workers .webworkers Modernizr.webworkers

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 47


applicationCache .applicationcache Modernizr.applicationcache

SVG .svg Modernizr.svg

SVG Clip Paths .svgclippaths Modernizr.svgclippaths

SMIL .smil Modernizr.smil

Web SQL Database .websqldatabase Modernizr.websqldatabase

IndexedDB .indexeddb Modernizr.indexeddb

Web Sockets .websockets Modernizr.websockets

Hashchange Event .hashchange Modernizr.hashchange

History Management .historymanagement Modernizr.historymanagement

Drag and Drop .draganddrop Modernizr.draganddrop

Cross-window .crosswindowmessaging Modernizr.crosswindowmessaging


Messaging

addTest Plugin API NA Modernizr.addTeststr,fn

13. HTML5 Notifications


Nowadays, we are seeing a change in the behavior of desktop/mobile websites.
Websites are starting to emulate app-like behavior; one of them primarily being
notifications. Users have multiple tabs open their browser and they get notifications
inside the browser itself, like a chat message, a tweet or Facebook notification.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 48


In this tutorial, we’ll show you how to integrate HTML5s Notification API to send and
receive realtime notifications and alerts in the browser. You can learn more about
Notification API methods and support from Notification API docs (MDN).

Index.html
It begins with a basic HTML5 boilerplate with CDN for jQuery and PubNub.

<script src="https://cdn.pubnub.com/pubnub-3.7.13.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
Then, inside the body tag, we added a button calling a JavaScript function to test the
Notification functionality.

<button onclick="notifyMe()">Notify me!</button>


Here is how the notifyMe function looks like:

function notifyMe(message) {

if (message == undefined) {
message = "Hi there! You clicked a button.";
};
Here it checks if the function is getting any parameters. If not, we are setting a message
as on clicking the button no message is being passed.

if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
}

else if (Notification.permission === "granted") {


var notification = new Notification(message);
}

else if (Notification.permission !== 'denied') {


Notification.requestPermission(function (permission) {
if (permission === "granted") {
var notification = new Notification("Hi there!");
}

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 49


});
}
This block checks if the browser supports notifications. If it supports, then we check
whether notification permissions have already been granted. If not, we need to ask the
user for permission. If they allow, then we are good to go to create notifications and we
pass the message parameters to the notification.

So we have a basic our HTML5 notification API working. Now we need to get the
messages from PubNub’s channel and pass it to notification API to make these
notifications really realtime.

$(document).ready(function() {
var pubnub = PUBNUB({
subscribe_key : 'demo'
});

pubnub.subscribe({
channel : "pubnub-html5-notification-demo", // Subscribing to PubNub's channel
message : function(message){
console.log(message);
notifyMe(message.text);
}
})
});

14. Drag and Drop API

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.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 50


Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD
support to the browser making it much easier to code up.

HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and
Safari 4 etc.

Drag and Drop Events


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

Sr.No. Events & Description

1 dragstart

Fires when the user starts dragging of the object.

dragenter

Fired when the mouse is first moved over the target element while a
2
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.

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

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 51


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.

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

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

The DataTransfer Object


The event listener methods for all the drag and drop events accept Eventobject which
has a readonly attribute called dataTransfer.

The event.dataTransfer returns DataTransfer object associated with the event as


follows −

function EnterHandler(event) {

DataTransfer dt = event.dataTransfer;

.............

The DataTransfer object holds data about the drag and drop operation. This data can be
retrieved and set in terms of various attributes associated with DataTransfer object as
explained below −

Sr.No. DataTransfer attributes and their description

dataTransfer.dropEffect [ = value ]

 Returns the kind of operation that is currently selected.


1
 This attribute can be set, to change the selected operation.

 The possible values are none, copy, link, and move.

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 52


dataTransfer.effectAllowed [ = value ]

 Returns the kinds of operations that are to be allowed.


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

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

data = dataTransfer.getData(format)
6
Returns the specified data. If there is no such data, returns the empty
string.

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

9 dataTransfer.addElement(element)

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 53


Adds the given element to the list of elements used to render the drag
feedback.

Drag and Drop Process


Following are the steps to be carried out to implement Drag and Drop operation −

Step 1 - Making an Object Draggable


Here are steps to be taken −

 If you want to drag an element, you need to set the draggableattribute


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 −

<!DOCTYPE HTML>

<html>

<head>

<style type = "text/css">

#boxA, #boxB {

float:left;padding:10px;margin:10px; -moz-user-select:none;

#boxA { background-color: #6633FF; width:75px; height:75px; }

#boxB { background-color: #FF6699; width:150px; height:150px; }

</style>

<script type = "text/javascript">

function dragStart(ev) {

ev.dataTransfer.effectAllowed = 'move';

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 54


ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));

ev.dataTransfer.setDragImage(ev.target,0,0);

return true; }

</script>

</head>

<body>

<center>

<h2>Drag and drop HTML5 demo</h2>

<div>Try to drag the purple box around.</div>

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

ondragstart = "return dragStart(ev)">

<p>Drag Me</p>

</div>

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

</center>

</body></html>

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.

<html>

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 55


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

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 56


2. Explain why HTML5 is called the Nest Generation of Web
development

HTML5 is being developed with emerging features such as Cascading Style Sheets (CSS3), RIA,
and Mobile Web. Its impact on the Web industry will be significant. The other issue is whether
it is possible and desirable to replace Operating Systems with Next Generation Web. In
considering all of these issues in various applications of Next Generation Web, using
interoperable standardized technologies would be extremely useful for seamless fixed and
mobile Web services delivery over the Internet. In that sense, the following recent Web
technology standard issues of W3C show some clues to the future direction of Next Generation
Web.

1. Device API standards for Mobile Web device control


2. Video Web standards toward common metadata for diverse Web-based video
services
3. Mobile Web standards for seamless Web services access using diverse Mobile Web
devices
4. RIA standards for Web applications for including widgets
5. HTML5 standards toward comprehensive Web markup specification
6. Social Web standards Web-based social services using Semantic Web technologies

Future development direction of next generation Web technologies


The following list of standard organization organizations (SDOs) have been working on
the emerging technologies of Next Generation Web.
• Consumer Electronics Linux Forum (CELF)
• Digital Video Broadcasting Project (DVB)
• Electronic Product Code (EPC)
• Institute of Electrical & Electronics Engineers, Inc. (IEEE)

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 57


• International Organization for Standardization (ISO)
• International Telecommunication Union (ITU)
• Java Community Process (JCP) • Moving Pictures Expert Group (MPEG)
• Open Geospatial Consortium (OGC)
• Open Mobile Alliance (OMA)
• Object Management Group (OMG)
• World Wide Web Consortium (W3C)
• 3rd Generation Partnership Object (3GPP)

WEB TECHNOLOGY ASSIGNMENT - 1947234 Page 58

You might also like