Uploaded by Anushka Chaubey

CSE 352-Unit 1 3 HTML 5

advertisement
UNIT 1
HTML 5
What is HTML5?
• HTML5 is the next major revision of the HTML standard superseding HTML 4.01,
XHTML 1.0, and XHTML 2.0. HTML5 is a standard for structuring and presenting
content on the World Wide Web.
• HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the
Web Hypertext Application Technology Working Group (WHATWG).
• The new standard incorporates features like video playback and drag-and-drop
that have been previously dependent on third-party browser plug-ins such as
Adobe Flash, Microsoft Silverlight, and Google Gears.
Goals of HTML5
• Support all existing web pages. With HTML5, there is no requirement to go back and revise
older websites.
• Reduce the need for external plugins and scripts to show website content.
• Improve the semantic definition (i.e. meaning and purpose) of page elements.
• Make the rendering of web content universal and independent of the device being used.
• Handle web documents errors in a better and more consistent fashion.
Browser Support for HTML 5
• The latest versions of Apple Safari, Google Chrome, Mozilla Firefox,
and Opera all support many HTML5 features and Internet Explorer 9.0
will also have support for some HTML5 functionality.
• The mobile web browsers that come pre-installed on iPhones, iPads,
and Android phones all have excellent support for HTML5.
HTML 5 new features
HTML5 introduces a number of new elements and attributes that helps in building a modern website. Following are great features
introduced in HTML5.
• New Semantic Elements − These are like
<header>, <footer>, and <section>.
What are Semantic Elements?
A semantic element clearly describes its
meaning to both the browser and the
developer.
Examples of non-semantic elements:
<div> and <span> - Tells nothing
about its content.
Examples of semantic elements:
<form>, <table>, and <article> -
Clearly defines its content.
• Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag.
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.
for <input> tag – datetime, date, time, email, url, month, week, datetime-local,number, range
• Persistent Local Storage- With local storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is
more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same
data.
• WebSocket − A next-generation bidirectional communication technology for web applications.
• Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they
are called Server-Sent Events (SSE).
• Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript.
• Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins.
HTML5 features, include native audio and video support without the need for Flash.
• Geolocation − Now visitors can choose to share their physical location with your web application.
• Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom
semantics.
• Drag and drop − Drag and drop the items from one location to another location on the same webpage.
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.
Basic HTML5 Web Page
we have our first complete web page in HTML5:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My First HTML5 Page</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<p>HTML5 is fun!</p>
</body>
</html>
HTML 5 is case insenisitive
• DOCTYPE :- <!DOCTYPE html>
• Character encoding : <meta charset=“UTF-8”>
• <script> tag: <script src=“scriptfile.js”></script>
• <link> tag : <link rel=“stylesheet” href=“stylefile.css”>
HTML 5 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.
example: <p> ………… </p>
• Some elements, however, are forbidden from containing any content
at all and these are known as void elements. For example, br, hr, link
and meta etc.
HTML 5 attributes
• Elements may contain attributes that are used to set various properties of
an element.
• Some attributes are defined globally and can be used on any element,
while others are defined for specific elements only.
• Attributes may only be specified within start tags and must never be used
in end tags.
• HTML5 attributes are case insensitive and may be written in all upper case
or mixed case, although the most common convention is to stick with
lower case.
Example: <div class=“example”>………..</div>
HTML5 Document
• The following tags have been introduced for better structure −
• section − This tag represents a generic document or application section. It can be used together with h1-h6 to indicate
the document structure.
• article − This tag represents an independent piece of content of a document, such as a blog entry or newspaper article.
• aside − This tag represents a piece of content that is only slightly related to the rest of the page.
• header − This tag represents the header of a section.
• footer − This tag represents a footer for a section and can contain information about the author, copyright information,
etc.
• nav − This tag represents a section of the document intended for navigation.
• dialog − This tag can be used to mark up a conversation.
• figure − This tag can be used to associate a caption together with some embedded content, such as a graphic or video.
output
CANVAS
Introduction: canvas
• HTML5 element <canvas> gives you an easy and powerful way to draw
graphics using JavaScript. It can be used to draw graphs, make photo
compositions or do simple (and not so simple) animations.
• The HTML <canvas> element is used to draw graphics on a web page via
JavaScript.
• The <canvas> element is only a container for graphics. You must use
JavaScript to actually draw the graphics.
• Canvas has several methods for drawing paths, boxes, circles, text, and
adding images.
What canvas can do ?
• HTML Canvas Can Draw Text
Canvas can draw colorful text, with or without animation.
• HTML Canvas Can Draw Graphics
Canvas has great features for graphical data presentation with an imagery of graphs and charts.
• HTML Canvas Can be Animated
Canvas objects can move. Everything is possible: from simple bouncing balls to complex animations.
• HTML Canvas Can be Interactive
Canvas can respond to JavaScript events.
Canvas can respond to any user action (key clicks, mouse clicks, button clicks, finger movement).
• HTML Canvas Can be Used in Games
Canvas' methods for animations, offer a lot of possibilities for HTML gaming applications.
CANVAS COORDINATES
• The canvas is a 2D grid. The coordinate (0, 0) is at the upper-left corner of the canvas. Along
the X-axis, values increase towards the right edge of the canvas. Along the Y-axis, values
increase towards the bottom edge of the canvas.
That coordinate diagram was drawn with
a <canvas> element. It comprises:
•a set of off-white vertical lines
•a set of off-white horizontal lines
•two black horizontal lines
•two small black diagonal lines that form an
arrow
•two black vertical lines
•two small black diagonal lines that form
another arrow
•the letter “x”
•the letter “y”
•the text “(0, 0)” near the upper-left corner
•the text “(500, 375)” near the lower-right
corner
•a dot in the upper-left corner, and another in
the lower-right corner
• A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.
First, we need to define the <canvas> element itself. The <canvas> element defines the width and height, and the id so
we can find it later.
<canvas id="c" width="500" height="375"></canvas>
Then we need a script to find the <canvas> element in the DOM and get its drawing context.
var c_canvas = document.getElementById("c");
var context = c_canvas.getContext("2d");
Now we can start drawing lines.
Example of a basic, empty canvas:
EXAMPLE
<!DOCTYPE html>
<html>
<body>
• <canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
• </canvas>
Output:
</body>
</html>
If something is
wrong then
output will be:-
Your browser does not support the HTML5 canvas tag.
The Rendering Context
• The <canvas> is initially blank, and to display something, a script first needs to access the rendering context
and draw on it.
• The canvas element has a DOM method called getContext, used to obtain the rendering context and its
drawing functions. This function takes one parameter, the type of context 2d.
• Following is the code to get required context along with a check if your browser supports <canvas> element −
var canvas = document.getElementById("mycanvas");
if (canvas.getContext)
{
var ctx = canvas.getContext('2d'); // drawing code here
}
else
{ // canvas-unsupported code here
}
Draw a line
s.no
method
discription
1
beginPath()
This method resets the current path
2
moveTo(x, y)
defines the starting point of the line
3
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the
same as the start and end of the newly closed subpath.
4
fill()
This method fills the subpaths with the current fill style.
5
stroke()
This method strokes the subpaths with the current stroke style.
6
lineTo(x, y)
defines the ending point of the line
Draw a circle
• To draw a circle on a canvas, use the following methods:
• beginPath() - begins a path
• arc(x,y,r,startangle,endangle) - creates an arc/curve. To create a circle with arc(): Set
start angle to 0 and end angle to 2*Math.PI. The x and y parameters define the xand y-coordinates of the center of the circle. The r parameter defines the radius of
the circle.
Example:
Define a circle with the arc() method. Then use the stroke() method to actually draw
the circle:
• var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Draw a text
• To draw text on a canvas, the most important property and methods are:
font - defines the font properties for the text
fillText(text,x,y) - draws "filled" text on the canvas
strokeText(text,x,y) - draws text on the canvas (no fill)
a) Using fill text()
Example:
Set font to 30px "Arial" and write a filled text on the
canvas:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
b) Using stroke text()
Example:
Set font to 30px "Arial" and write a text, with no fill, on the
canvas:
• var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
Add color and center text
Example:
Set font to 30px "Comic Sans MS" and write a filled red text in the center of the canvas:
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Hello World", canvas.width/2, canvas.height/2);
Canvas – Gradients
• Gradients can be used to fill rectangles, circles, lines, text, etc. Shapes on the canvas are not
limited to solid colors.
• There are two different types of gradients:
createLinearGradient(x,y,x1,y1) - creates a linear gradient
createRadialGradient(x,y,r,x1,y1,r1) - creates a radial/circular gradient
• Once we have a gradient object, we must add two or more color stops.
• The addColorStop() method specifies the color stops, and its position along the gradient.
Gradient positions can be anywhere between 0 to 1.
• To use the gradient, set the fillStyle or strokeStyle property to the gradient, then draw the
shape (rectangle, text, or a line).
a) Draw Linear gradient
Example:
Create a linear gradient. Fill rectangle with the gradient:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
Note: The fillStyle property can be a CSS color, a gradient, or a pattern. The default fillStyle is black.
The fillRect(x,y,width,height) method draws a rectangle, filled with the fill style, on the canvas:
b) Draw circular gradient
Example:
Radial gradients are defined with two imaginary circles - a starting circle and an ending circle,
in which the gradient starts with the start circle and moves towards the end circle.
Context.createRadialGradient(x0,y0,r0,x1,y1,r1);
X0: The starting circle of the gradient is X-axis
y0:-The starting circle of the gradient is Y-axis
R0: Radius of the start circle x1:-The starting circle of the gradient is x-axis
y1:-The ending circle of the gradient is Yaxis r1: Radius of the end circle
Create a radial/circular gradient. Fill rectangle with the gradient:
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
<!DOCTYPE html>
<html>
<body
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createRadialGradient(75,50,5,90,60,100);
grd.addColorStop(0,"red");
grd.addColorStop(0.3,"blue");
grd.addColorStop(1,"yellow");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
</body>
</html>
Offline pages
• Offline Web pages are Web pages you can view without being connected to the
Internet.
• There are many possible reasons for viewing an offline Web page – for example,
you may want to access important business information but have an Internet
connection that is either intermittent or limited in some way, such as in bandwidth
or speed.
• Some people manually save certain Web pages for viewing offline.
• Your Web browser may also save copies of Web pages, or parts of them, within its
cache memory.
• Emerging Web development technologies are improving the ability to manage
offline access to Web content.
Connections
• Internet connections often involve restrictions of various types. This is particularly the case with
mobile computing devices such as smartphones.
• If you use a mobile device to access websites over your mobile phone network, there may be times
when the connection is not available. This frequently occurs when a smartphone is in an area with
no network coverage. Offline Web pages can prove useful in these situations.
• Viewing Web content offline can also reduce the amount of data transfer, which can reduce datacap costs.
Cache
• Some Web browsers cache Web pages, or parts of pages.
For example, to minimize data transfer over the Internet, your browser may save a cached copy of
a media file such as an image or video – or sometimes the entire page – on your computer. The next
time you visit the page, your browser shows you the cached copy, rather than fetching the page and
content over the Web again.
• Internet Explorer saves copies of previously viewed pages in its store of temporary Internet files.
You can view these within the browser, even if you do not have an Internet connection.
Saving
• In some cases, website visitors choose to save pages for future viewing offline.
• To save Web pages, you can use a variety of applications and services. Most browsers,
including Internet Explorer, Firefox and Chrome, provide options for saving Web pages by
clicking "File" and "Save As." However, saved pages do not always appear in the same way
when viewed offline. Some browser add-ons and extensions enhance the ability to save
pages for later viewing offline.
HTML5
• With HTML5, developers can create pages that are designed to support viewing offline.
• However, there are many website functions that simply cannot work offline, such as those
involving databases and server scripting.
• https://support.microsoft.com/en-in/help/196646/how-to-makeweb-pages-available-for-offline-viewing
HTML MEDIA
a) Video
b) Audio
• Multimedia on the web is sound, music, videos, movies, and animations.
• HTML5 features, include native audio and video support without the need for Flash.
What is Multimedia?
• Multimedia comes in many different formats. It can be almost anything you can hear or see.
• Examples: Images, music, sound, videos, records, films, animations, and more.
• Web pages often contain multimedia elements of different types and formats.
Browser Support
• The first web browsers had support for text only, limited to a single font in a single color.
• Later came browsers with support for colors and fonts, and images!
• Audio, video, and animation have been handled differently by the major browsers. Different
formats have been supported, and some formats require extra helper programs (plug-ins) to
work.
Multimedia Formats
• Multimedia elements (like audio or video) are stored in media files.
• The most common way to discover the type of a file, is to look at the file
extension.
• Multimedia files have formats and different extensions like: .swf, .wav, .mp3,
.mp4, .mpg, .wmv, and .avi.
Video formats
Audio formats
a) HTML video
Playing Videos in HTML
• Before HTML5, a video could only be played in a browser with a plug-in (like flash).
• The HTML5 <video> element specifies a standard way to embed a video in a web page.
Example
<!DOCTYPE html>
<html>
<body>
How it works?
The controls attribute adds video controls, like play, pause,
and volume.
<video width="320" height="240" controls>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
It is a good idea to always
include width and height attributes. If height and width are
not set, the page might flicker while the video loads
.
The <source> element allows you to specify alternative
video files which the browser may choose from. The
browser will use the first recognized format.
</body>
</html>
The text between the <video> and </video> tags will only
be displayed in browsers that do not support the <video>
element.
HTML <video> Autoplay
• To start a video automatically use the autoplay attribute:
<video width="320" height="240" autoplay>
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
HTML Video - Browser Support
• In HTML5, there are 3 supported video formats: MP4, WebM, and Ogg.
Video tag attribute
• The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities
of the control −
a) HTML audio
• Before HTML5, audio files could only be played in a browser with a plug-in (like flash).
• The HTML5 <audio> element specifies a standard way to embed audio in a web page.
How it works?
The HTML <audio> Element
• To play an audio file in HTML, use the <audio> element:
<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
The controls attribute adds audio controls, like play,
pause, and volume.
The <source> element allows you to specify
alternative audio files which the browser may
choose from. The browser will use the first
recognized format.
The text between the <audio> and </audio> tags will
only be displayed in browsers that do not support
the <audio> element.
HTML Audio - Browser Support
• In HTML5, there are 3 supported audio formats: MP3, Wav, and Ogg.
• The browser support for the different formats is:
Audio tag attribute
• The HTML5 audio tag can have a number of attributes to control the look and feel and
various functionalities of the control:
GEO-LOCATION
• The HTML Geolocation API is used to locate a user's position.
Locate the User's Position
• The HTML Geolocation API is used to get the geographical position of a user.
• Since this can compromise privacy, the position is not available unless the user approves it.
• 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 API will only work on secure contexts such as HTTPS. If your site is hosted
on an non-secure origin (such as HTTP) the requests to get the users location will no longer
function.
Geolocation is also very useful for location-specific information, like:
• Up-to-date local information
• Showing Points-of-interest near the user
• Turn-by-turn navigation (GPS)
Geolocation object
• The geolocation API is published through the navigator.geolocation object.
• The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.
• If the object exists, geolocation services are available. You can test for the presence of geolocation thusly:
if ("geolocation" in navigator)
{ /* geolocation is available */
}
else
{ /* geolocation IS NOT available */
}
• 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;
Geolocation Methods: Getting the current position
1)
getCurrentPosition method :To obtain the user's current location, you can call the getCurrentPosition() method.
syntax:
getCurrentPosition(function(showLocation), ErrorHandler, options);
• showLocation − This specifies the callback method that retrieves the location information. This
method is called asynchronously with an object corresponding to the Position object which stores
the returned location information.
• ErrorHandler − This optional parameter specifies the callback method that is invoked when an
error occurs in processing the asynchronous call. This method is called with
the PositionError object that stores the returned error information.
• options − This optional parameter specifies a set of options for retrieving the location
information. You can specify (a) Accuracy of the returned location information (b) Timeout for
retrieving the location information and (c) Use of cached location information .
<!DOCTYPE html>
<html> <body>
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation()
{ if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else
{ x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position)
{
x.innerHTML = "Latitude: " + position.coords.latitude
+ "<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Output 1 :-
Output 2 :-
Example explained:
• Check if Geolocation is supported
• If supported, run the getCurrentPosition() method. If not, display a
message to the user
• If the getCurrentPosition() method is successful, it returns a
coordinates object to the function specified in the parameter
(showPosition)
• The showPosition() function outputs the Latitude and Longitude
Handling errors and rejections paramtere:
• The second parameter of the getCurrentPosition() method is used to handle errors. It specifies a function to run if it fails to
get the user's location:
• function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
Position Options parameter
• It describes the options to use while retrieving the user’s location.
• enableHighAccuracy: Boolean. If true, the user agent will try to provide the most
accurate position. This can result in slower response time and higher power
consumption. Is false, less accurate position will be obtained. Default value is false.
• Timeout: Positive long value. It denotes the maximum time (in milliseconds) that the
user agent can take to respond with the location data. Default value is Infinity.
• maximumAge: Positive long value. It denotes how long (in milliseconds) the user
agent can keep using the cached location data before trying to obtain new location
data. A zero value indicates that the user agent must not use the cached location
data and infinity value indicates that the cached location data must be used by the
user agent.
if (navigator.geolocation)
{
var optn = { enableHighAccuracy : true,
timeout : Infinity,
maximumAge : 0
};
navigator.geolocation.getCurrentPosition(showPosition, showError, optn);
}
else
{
alert('Geolocation is not supported in your browser');
}
• The getCurrentPosition() Method - Return Data
• The getCurrentPosition() method returns an object on success. The latitude, longitude and accuracy
properties are always returned. The other properties are returned if available:
2) Watching the current position- Watchposition()
• Returns the current position of the user and continues to return updated position as the user moves (like the
GPS in a car).
• The location information is returned in a Position object. Each update returns a new Position object.
syntax: watchPosition(showLocation, ErrorHandler, options);
• Called multiple times.
Watchposition Example
• <script>
var x = document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.watchPosition(showPosition);
}
else
{
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position)
{
x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
}
</script>
3) Clearwatch()
•
Stops the watchPosition() method. The clearWatch method cancels an ongoing
watchPosition call. When cancelled, the watchPosition call stops retrieving updates about
the current geographic location of the device.
syntax: navigator.geolocation.clearWatch(watchID);
watchId − This specifies the unique ID of the watchPosition call to cancel. The ID is returned
by the watchPosition call.
Return value : The clearWatch method does not return a value
HTML5 Local 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 Web Storage API provides mechanisms by which browsers can store key/value pairs, in a
much more intuitive fashion than using cookies.
The two storage's are session storage and local storage and they would be used to handle
different situations.
What is HTML web Storage?
HTML web storage; better than cookies.
• With web storage, web applications can store data locally within the user's browser.
• Before HTML5, application data had to be stored in cookies, included in every server request. web storage is
more secure, and large amounts of data can be stored locally, without affecting website performance.
• Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
(web storage storage limit-10 MB)
• web storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same
data.
• Simply put, web storage allows large amounts of application data to be be stored locally, without affecting
your web application’s performance.
HTML web Storage Objects
HTML web storage provides two objects for storing data on the client:
1) window.localStorage –
does the same thing of storing data , but persists even when the browser is
closed and reopened.
it stores data with no expiration date.
2) window.sessionStorage –
stores data for one session (data is lost when the browser tab is closed)
maintains a separate storage area for each given origin that's available for
the duration of the page session (as long as the browser is open, including
page reloads and restores)
a) The web storage object
• The localStorage object stores the data with no expiration date. The data will not be deleted when the browser
is closed, and will be available the next day, week, or year.
<div id="result"></div>
Output:
<script>
if (typeof(Storage) !== "undefined") // Check browser support
{ localStorage.setItem("lastname", "Smith");
// Store
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
// Retrieve
}
else
{
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>
Explanation : Create a localStorage name/value pair with name="lastname" and value="Smith"
Retrieve the value of "lastname" and insert it into the element with id="result"
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
Above code of previous slide can also be written as:
localStorage.lastname = "Smith";
// Store
document.getElementById("result").innerHTML = localStorage.lastname;
// Retrieve
Removing local storage
Web Storage also provides a couple of simple methods to remove data.
a) Storage.removeItem() takes a single argument — the key of the data item you want to remove —
and removes it from the storage object for that domain
b) Storage.clear() takes no arguments, and simply empties the entire storage object for that domain.
Example:
localStorage.removeItem("lastname");
b) SessionStorage object
• The sessionStorage object is equal to the localStorage object, except that it stores the
data for only one session.
• The data is deleted when the user closes the specific browser tab.
Example : The following example counts the number of times a user has clicked a button, in the
current session:
if (sessionStorage.clickcount)
{
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
}
else
{
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
Cookie Vs Session
• Cookies are stored in browser as text file format.
• It is stored limit amount of data. It is only allowing 4kb[4096bytes]
• It is not holding the multiple variable in cookies.
• We can accessing the cookies values in easily. So it is less secure.
• The setcookie() function must appear BEFORE the tag.
• A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer
requests a page with the browser, it will send the cookie too.
• it maintaines user identification means it tracks visitors record.
session
• Session is used for maintaining a dialoge between server and user.
• it is more secure because it is stored on the server, we can not easily
access it. it embeds cookies on the user computer.
• it stores unlimited data.
• A session is used to store information about, or change setting for a
user session.
• Session variable hold the information about single user, and are
available to all pages in one application.
• It is holding the multiple variable in sessions.
Download