187
HTML5 Rakesh Kumar Jha M.Tech, MBA

Advanced html5 for android application development in phonegap

Embed Size (px)

DESCRIPTION

What is HTML5, How to use HTML5 in Phonegap ? History, Vision And Future Of HTML5 Getting Started With HTML5 Structure Of A Web Page CSS3 Introduction Forms Audio And Video HTML5 Canvas Hands-on exercises Data Storage HTML5 Web Workers HTML5 Messaging APIs HTML5 Web Sockets HTML5 Offline Web Applications Hands-on exercises

Citation preview

Page 1: Advanced html5 for android application development in phonegap

HTML5

Rakesh Kumar Jha

M.Tech, MBA

Page 2: Advanced html5 for android application development in phonegap

Contents

• HTML5 Home

• HTML5 Forms

• HTML5 Reference

• HTML5 Tags

• HTML5 Canvas

• Audio And Video

Page 3: Advanced html5 for android application development in phonegap

HTML5 is The New HTML Standard

HTML5 new features • New Elements • New Attributes • Full CSS3 Support • Video and Audio • 2D/3D Graphics • Local Storage • Local SQL Database • Web Applications

Page 4: Advanced html5 for android application development in phonegap

HTML5 Introduction

HTML5 is the next generation of HTML

What is HTML5?

• HTML5 will be the new standard for HTML, XHTML, and the HTML DOM.

• The previous version of HTML came in 1999.

• HTML5 is still a work in progress. However, most modern browsers have some HTML5 support.

Page 5: Advanced html5 for android application development in phonegap

How Did HTML5 Get Started?

HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG).

WHATWG was working with web forms and applications, and W3C was working with XHTML 2.0. In 2006, they decided to cooperate and create a new version of HTML.

Page 6: Advanced html5 for android application development in phonegap

How Did HTML5 Get Started?

Some rules for HTML5 were established:

• New features should be based on HTML, CSS, DOM, and JavaScript

• Reduce the need for external plugins (like Flash)

• Better error handling

• More markup to replace scripting

• HTML5 should be device independent

• The development process should be visible to the public

Page 7: Advanced html5 for android application development in phonegap

New Features

Some of the most interesting new features in HTML5:

• The canvas element for drawing

• The video and audio elements for media playback

• Better support for local offline storage

• New content specific elements, like article, footer, header, nav, section

• New form controls, like calendar, date, time, email, url, search

Page 8: Advanced html5 for android application development in phonegap

Browser Support

• HTML5 is not yet an official standard, and no browsers have full HTML5 support.

• But all major browsers (Safari, Chrome, Firefox, Opera, Internet Explorer) continue to add new HTML5 features to their latest versions.

Page 9: Advanced html5 for android application development in phonegap

New Markup Elements

• Today, some elements in HTML 4.01 are obsolete, never used, or not used the way they were intended to. These elements are deleted or re-written in HTML5.

• To better handle today's internet use, HTML5 also includes new elements for better structure, drawing, media content, and better form handling.

Page 10: Advanced html5 for android application development in phonegap

New Elements in HTML5 Tag Description

<article> Specifies independent, self-contained content, could be a news-article, blog post, forum post, or other articles which can be distributed independently from the rest of the site.

<aside> For content aside from the content it is placed in. The aside content should be related to the surrounding content

<bdi> For text that should not be bound to the text-direction of its parent elements

<command> A button, or a radiobutton, or a checkbox

<details> For describing details about a document, or parts of a document

summary> A caption, or summary, inside the details element

<figure> For grouping a section of stand-alone content, could be a video

<figcaption> The caption of the figure section

<section> For a section in a document. Such as chapters, headers, footers, or any other sections of the document

<time> For defining a time or a date, or both

Page 11: Advanced html5 for android application development in phonegap

New Markup Elements Tag Description

<footer> For a footer of a document or section, could include the name of the author, the date of the document, contact information, or copyright information

<header> For an introduction of a document or section, could include navigation

<hgroup> For a section of headings, using <h1> to <h6>, where the largest is the main heading of the section, and the others are sub-headings

<mark> For text that should be highlighted

<meter> For a measurement, used only if the maximum and minimum values are known

<nav> For a section of navigation

<progress> The state of a work in progress

<ruby> For ruby annotation (Chinese notes or characters)

<rt> For explanation of the ruby annotation

<rp> What to show browsers that do not support the ruby element

<wbr> Word break. For defining a line-break opportunity.

Page 12: Advanced html5 for android application development in phonegap

New Media Elements

Tag Description

<audio> For multimedia content, sounds, music or other audio streams

<video> For video content, such as a movie clip or other video streams

<source> For media resources for media elements, defined inside video or audio elements

<embed> For embedded content, such as a plug-in

<track> For text tracks used in mediaplayers

Page 13: Advanced html5 for android application development in phonegap

The Canvas Element

Tag Description

<canvas> For making graphics with a script

The canvas element uses JavaScript to make drawings on a web page.

Page 14: Advanced html5 for android application development in phonegap

New Form Elements

Tag Description

<datalist> A list of options for input values

<keygen> Generate keys to authenticate users

<output> For different types of output, such as output written by a script

HTML5 offers more form elements, with more functionality:

Page 15: Advanced html5 for android application development in phonegap

New Input Type Attribute Values Type Description

tel The input value is of type telephone number

search The input field is a search field

url The input value is a URL

email The input value is one or more email addresses

datetime The input value is a date and/or time

date The input value is a date

month The input value is a month

week The input value is a week

time The input value is of type time

datetime-local The input value is a local date/time

number The input value is a number

range The input value is a number in a given range

color The input value is a hexadecimal color, like #FF8800

placeholder Specifies a short hint that describes the expected value of an input field

Page 16: Advanced html5 for android application development in phonegap

HTML5 Video

Today, most videos are shown through a plug-in (like flash). However, different browsers may have different plug-ins.

HTML5 defines a new element which specifies a standard way to embed a video/movie on a web page: the <video> element.

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

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

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

Page 17: Advanced html5 for android application development in phonegap

HTML5 Video

• You should also insert text content between the <video> and </video> tags for browsers that do not support the <video> element.

• The <video> element allows multiple <source> elements. <source> elements can link to different video files. The browser will use the first recognized format.

Page 18: Advanced html5 for android application development in phonegap

Video Formats and Browser Support

Browser MP4 WebM Ogg

Internet Explorer 9 YES NO NO

Firefox 4.0 NO YES YES

Google Chrome 6 YES YES YES

Apple Safari 5 YES NO NO

Opera 10.6 NO YES YES

Currently, there are 3 supported video formats for the <video> element: MP4, WebM, and Ogg:

•MP4 = MPEG 4 files with H264 video codec and AAC audio codec •WebM = WebM files with VP8 video codec and Vorbis audio codec •Ogg = Ogg files with Theora video codec and Vorbis audio codec

Page 19: Advanced html5 for android application development in phonegap

HTML5 video Tags Tag Description

<video> Defines a video or movie

<source> Defines multiple media resources for media elements, such as <video> and <audio>

<track> Defines text tracks in mediaplayers

Page 20: Advanced html5 for android application development in phonegap

HTML5 Video + DOM

HTML5 <video> - Take Control Using the DOM The HTML5 <video> element also has methods,

properties, and events. There are methods for playing, pausing, and loading, for

example. There are properties (e.g. duration, volume, seeking) that

you can read or set. There are also DOM events that can notify you, for example, when the <video> element begins to play, is paused, is ended, etc.

The example below calls two methods: play() and pause(). It also uses three properties: paused, height and videoHeight.

Page 21: Advanced html5 for android application development in phonegap

HTML5 Video + DOM

<!DOCTYPE html> <html> <body> <div style="text-align:center"> <button onclick="playPause()">Play/Pause</button> <button onclick="makeBig()">Big</button> <button onclick="makeSmall()">Small</button> <button onclick="makeNormal()">Normal</button> <br /> <video id="video1"> <source src="mov_bbb.mp4" type="video/mp4" /> <source src="mov_bbb.ogg" type="video/ogg" /> Your browser does not support HTML5 video. </video> </div>

Page 22: Advanced html5 for android application development in phonegap

HTML5 Video + DOM

<script type="text/javascript">

var myVideo=document.getElementById("video1");

function playPause()

{

if (myVideo.paused)

myVideo.play();

else

myVideo.pause();

}

function makeBig()

{

myVideo.height=(myVideo.videoHeight*2);

}

function makeSmall()

{

myVideo.height=(myVideo.videoHeight/2);

}

function makeNormal()

{

myVideo.height=(myVideo.videoHeight);

}

</script>

<p>Video courtesy of <a href="http://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p>

</body>

</html>

Page 23: Advanced html5 for android application development in phonegap

HTML5 <video> - Methods, Properties, and Events

Method Properties Events

play() currentSrc play

pause() currentTime pause

load() videoWidth progress

canPlayType videoHeight error

duration timeupdate

ended ended

error abort

paused empty

muted emptied

seeking waiting

volume loadedmetadata

height

width

Page 24: Advanced html5 for android application development in phonegap

HTML5 Audio

HTML5 defines a new element which specifies a standard way to embed an audio file on a web page: the <audio> element.

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

Page 25: Advanced html5 for android application development in phonegap

Audio Formats and Browser Support

Browser MP3 Wav Ogg

Internet Explorer 9 YES NO NO

Firefox 4.0 NO YES YES

Google Chrome 6 YES YES YES

Apple Safari 5 YES YES NO

Opera 10.6 NO YES YES

Currently, there are 3 supported file formats for the <audio> element: MP3, Wav, and Ogg:

<audio> Defines sound content

<source> Defines multiple media resources for media elements, such as <video> and <audio>

Page 26: Advanced html5 for android application development in phonegap

HTML5 Canvas

• The canvas element is used to draw graphics on a web page.

What is Canvas? • The HTML5 canvas element uses JavaScript to

draw graphics on a web page. • A canvas is a rectangular area, and you control

every pixel of it. • The canvas element has several methods for

drawing paths, boxes, circles, characters, and adding images.

Page 27: Advanced html5 for android application development in phonegap

Create a Canvas Element

• Add a canvas element to the HTML5 page.

• Specify the id, width, and height of the element:

<canvas id="myCanvas" width="200" height="100"></canvas>

Page 28: Advanced html5 for android application development in phonegap

Create a Canvas Element

• Draw With JavaScript

• The canvas element has no drawing abilities of its own. All drawing must be done inside a JavaScript:

<script type="text/javascript">

var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.fillRect(0,0,150,75); </script>

Page 29: Advanced html5 for android application development in phonegap

Draw With JavaScript - Line

<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.moveTo(10,10); ctx.lineTo(150,50); ctx.lineTo(10,50); ctx.stroke(); </script> </body> </html>

Page 30: Advanced html5 for android application development in phonegap

Draw With JavaScript - Circle

<!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;"> Your browser does not support the canvas element. </canvas> <script type="text/javascript"> var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="#FF0000"; ctx.beginPath(); ctx.arc(70,18,15,0,Math.PI*2,true); ctx.closePath(); ctx.fill(); </script> </body> </html>

Page 31: Advanced html5 for android application development in phonegap

Draw With JavaScript - Gradient

<!DOCTYPE html>

<html>

<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">

Your browser does not support the canvas element.

</canvas>

<script type="text/javascript">

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

var grd=ctx.createLinearGradient(0,0,175,50);

grd.addColorStop(0,"#FF0000");

grd.addColorStop(1,"#00FF00");

ctx.fillStyle=grd;

ctx.fillRect(0,0,175,50);

</script>

</body>

</html>

Page 32: Advanced html5 for android application development in phonegap

Draw With JavaScript - Image

<!DOCTYPE html>

<html>

<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">

Your browser does not support the canvas element.

</canvas>

<script type="text/javascript">

window.onload=function()

{

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

var img=new Image();

img.src="img_flwr.png";

ctx.drawImage(img,0,0);

}

</script>

</body>

</html>

Page 33: Advanced html5 for android application development in phonegap

Draw With JavaScript - Image

<!DOCTYPE html>

<html>

<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">

Your browser does not support the canvas element.

</canvas>

<script type="text/javascript">

window.onload=function()

{

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

var img=new Image();

img.src="img_flwr.png";

ctx.drawImage(img,0,0);

}

</script>

</body>

</html>

Page 34: Advanced html5 for android application development in phonegap

HTML5 Geolocation

HTML5 Geolocation is used to locate a user's position

Locate the User's Position

• The HTML5 Geolocation API is used to get the geographical position of a user.

• Since this can compromise user privacy, the position is not available unless the user approves it.

Page 35: Advanced html5 for android application development in phonegap

Browser Support

• Internet Explorer 9, Firefox, Chrome, Safari and Opera support Geolocation.

• Note: Geolocation is much more accurate for devices with GPS, like iPhone.

Page 36: Advanced html5 for android application development in phonegap

Using Geolocation

Use the getCurrentPosition() method to get the user's position. <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>

Page 37: Advanced html5 for android application development in phonegap

Using Geolocation

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 gets the displays the Latitude and Longitude

Page 38: Advanced html5 for android application development in phonegap

Handling Errors and Rejections - Geolocation

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;. } }

Page 39: Advanced html5 for android application development in phonegap

Handling Errors and Rejections - Geolocation

Error Codes:

• Permission denied - The user did not allow Geolocation

• Position unavailable - It is not possible to get the current location

• Timeout - The operation timed out

Page 40: Advanced html5 for android application development in phonegap

Displaying the Result in a Map

• To display the result in a map, you need access to a map service that can use latitude and longitude, like Google Maps:

function showPosition(position)

{ var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +latlon+"&zoom=14&size=400x300&sensor=false"; document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />"; }

Page 41: Advanced html5 for android application development in phonegap

<!DOCTYPE html> <html> <body> <p id="demo">Click the button to get your position:</p> <button onclick="getLocation()">Try It</button> <div id="mapholder"></div> <script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition,showError); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +latlon+"&zoom=14&size=400x300&sensor=false"; document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />"; } 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; } } </script> </body> </html>

Page 42: Advanced html5 for android application development in phonegap

Location-specific Information

Demonstrated how to show a user's position on a map. However, Geolocation is also very useful for location-specific information.

Examples:

• Up-to-date local information

• Showing Points-of-interest near the user

• Turn-by-turn navigation (GPS)

Page 43: Advanced html5 for android application development in phonegap

The getCurrentPosition() Method - Return Data

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude and accuracy properties are always returned. The other properties below are returned if available.

Property Description

coords.latitude The latitude as a decimal number

coords.longitude The longitude as a decimal number

coords.accuracy The accuracy of position

coords.altitude The altitude in meters above the mean sea level

coords.altitudeAccuracy The altitude accuracy of position

coords.heading The heading as degrees clockwise from North

coords.speed The speed in meters per second

timestamp The date/time of the response

Page 44: Advanced html5 for android application development in phonegap

Geolocation object - Other interesting Methods

• watchPosition() - Returns the current position of the user and continues to return updated position as the user moves (like the GPS in a car).

• clearWatch() - Stops the watchPosition() method.

• The example below shows the watchPosition() method. You need an accurate GPS device to test this (like iPhone):

Page 45: Advanced html5 for android application development in phonegap

Geolocation object - Other interesting Methods

<!DOCTYPE html> <html> <body> <p id="demo">Click the button to get your coordinates:</p> <button onclick="getLocation()">Try It</button> <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> </body> </html>

Page 46: Advanced html5 for android application development in phonegap

HTML5 Web Storage

Storing Data on the Client HTML5 offers two new objects for storing data on the client: • localStorage - stores data with no time limit • sessionStorage - stores data for one session • Earlier, this was done with cookies. Cookies are not suitable for

large amounts of data, because they are passed on by EVERY request to the server, making it very slow and in-effective.

• In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website's performance.

• HTML5 uses JavaScript to store and access the data.

Page 47: Advanced html5 for android application development in phonegap

The localStorage Object

• The localStorage object stores the data with no time limit. The data will be available the next day, week, or year.

• How to create and access a localStorage: <script type="text/javascript">

localStorage.lastname="Smith"; document.write(localStorage.lastname); </script>

Page 48: Advanced html5 for android application development in phonegap

The localStorage Object

he following example counts the number of times a user has visited a page:

<script type="text/javascript">

if (localStorage.pagecount) { localStorage.pagecount=Number(localStorage.pagecount) +1; } else { localStorage.pagecount=1; } document.write("Visits "+ localStorage.pagecount + " time(s)."); </script>

Page 49: Advanced html5 for android application development in phonegap

The sessionStorage Object

The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window.

<script type="text/javascript">

sessionStorage.lastname="Smith"; document.write(sessionStorage.lastname); </script>

Page 50: Advanced html5 for android application development in phonegap

HTML5 Forms

Page 51: Advanced html5 for android application development in phonegap

HTML5 Input Types

HTML5 New Input Types HTML5 has several new input types for forms. These new features allow better input control and

validation.

• color • date • datetime • datetime-local • email • month • number • range • search • tel • time • url • week Note: Not all major browsers support all the new input types. However, you can already start using

them; If they are not supported, they will behave as regular text fields.

Page 52: Advanced html5 for android application development in phonegap

Input Type: color

The color type is used for input fields that should contain a color <!DOCTYPE html> <html> <body>

<form action="demo_form.asp"> Select your favorite color: <input type="color" name="favcolor" /><br /> <input type="submit" /> </form>

</body> </html> Not supported – IE, Mozilla, chrome, Safari, Supported - Opera

Page 53: Advanced html5 for android application development in phonegap

Input Type: date

The date type allows the user to select a date (with time zone).

<!DOCTYPE html> <html>

<body>

<form action="demo_form.asp">

Birthday: <input type="date" name="bday" />

<input type="submit" />

</form>

</body>

</html>

Not supported – IE, Mozilla,

Supported - chrome, Safari, Opera

Page 54: Advanced html5 for android application development in phonegap

Input Type: datetime-local

The datetime-local type allows the user to select a date and time (no time zone).

<!DOCTYPE html>

<html>

<body> <form action="demo_form.asp">

Birthday (date and time): <input type="datetime-local" name="bdaytime" />

<input type="submit" />

</form>

</body>

</html>

Not supported – IE, Mozilla,

Supported - chrome, Safari, Opera

Page 55: Advanced html5 for android application development in phonegap

Input Type: email

The email type is used for input fields that should contain an e-mail address

<!DOCTYPE html> <html> <body>

<form action="demo_form.asp"> E-mail: <input type="email" name="usremail" /><br /> <input type="submit" /> </form>

</body> </html> Not supported – IE, Safari Supported - chrome, Mozilla, Safari, Opera

Page 56: Advanced html5 for android application development in phonegap

Input Type: month

The month type allows the user to select a month and year.

<!DOCTYPE html>

<html>

<body> <form action="demo_form.asp">

Birthday (month and year): <input type="month" name="bdaymonth" />

<input type="submit" />

</form>

</body>

</html>

Not supported – IE, Mozilla,

Supported - chrome, Safari, Opera

Page 57: Advanced html5 for android application development in phonegap

Input Type: number

• The number type is used for input fields that should contain a numeric value.

• You can also set restrictions on what numbers are accepted: <!DOCTYPE html> <html> <body>

<form action="demo_form.asp"> Quantity (between 1 and 5): <input type="number" name="quantity" min="1" max=“31"

/> <input type="submit" />

</form> </body> </html>

Not supported – IE, Mozilla, Supported - chrome, Safari, Opera

Page 58: Advanced html5 for android application development in phonegap

Input Type: number

• Use the following attributes to specify restrictions:

• max - specifies the maximum value allowed • min - specifies the minimum value allowed • step - specifies the legal number intervals • value - Specifies the default value <form action="demo_form.asp" method="get"> <input type="number" name="points" min="0" max="10" step="3" value="6" /> <input type="submit" /> </form>

Page 59: Advanced html5 for android application development in phonegap

Input Type: range

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

• You can also set restrictions on what numbers are accepted.

<form action="demo_form.asp" method="get">

Points: <input type="range" name="points" min="1" max="10" />

<input type="submit" />

</form>

Not supported – IE, Mozilla,

Supported - chrome, Safari, Opera

Page 60: Advanced html5 for android application development in phonegap

Input Type: search

The search type is used for search fields (a search field behaves like a regular text field).

<!DOCTYPE html>

<html>

<body> <form action="demo_form.asp">

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

<input type="submit" />

</form>

</body>

</html> Not supported – IE, Mozilla, Opera

Supported - chrome, Safari

Page 61: Advanced html5 for android application development in phonegap

Input Type: tel

Define a field for entering a telephone number: <!DOCTYPE html> <html> <body> <form action="demo_form.asp"> Telephone: <input type="tel" name="usrtel" /><br /> <input type="submit" /> </form> </body> </html> Not supported – IE, Mozilla, Opera, chrome, Safari

Page 62: Advanced html5 for android application development in phonegap

Input Type: time

• The time type allows the user to select a time. <!DOCTYPE html>

<html>

<body> <form action="demo_form.asp">

Select a time: <input type="time" name="usr_time" />

<input type="submit" />

</form>

</body>

</html>

Not supported – IE, Mozilla,

Supported - chrome, Safari, Opera

Page 63: Advanced html5 for android application development in phonegap

Input Type: url

• The url type is used for input fields that should contain a URL address. • The value of the url field is automatically validated when the form is

submitted. <!DOCTYPE html> <html> <body>

<form action="demo_form.asp"> Add your homepage: <input type="url" name="homepage" /><br /> <input type="submit" /> </form>

</body> </html> Not supported – IE, Safari, Opera Supported - chrome, Mozilla

Page 64: Advanced html5 for android application development in phonegap

Input Type: week

The week type allows the user to select a week and year.

<!DOCTYPE html> <html> <body>

<form action="demo_form.asp"> Select a week: <input type="week" name="year_week" /> <input type="submit" /> </form>

</body> </html> Not supported – IE, Mozilla, Supported - chrome, Safari, Opera

Page 65: Advanced html5 for android application development in phonegap

HTML5 Form Elements

Page 66: Advanced html5 for android application development in phonegap

HTML5 New Form Elements

HTML5 has several new elements and attributes for forms.

• <datalist>

• <keygen>

• <output>

Tag IE Firefox Opera Chrome Safari

<datalist> No 4.0 9.5 No No

<keygen> No 4.0 10.5 3.0 No

<output> No 4.0 9.5 10.0 5.1

Page 67: Advanced html5 for android application development in phonegap

<datalist> Element

• The <datalist> element specifies a list of options for an input field.

• The list is created with <option> elements inside the <datalist>

<form action="demo_form.asp" method="get"> Webpage: <input type="url" list="url_list" name="link" />

<datalist id="url_list"> <option label="W3Schools" value="http://www.w3schools.com" /> <option label="Google" value="http://www.google.com" /> <option label="Microsoft" value="http://www.microsoft.com" /> </datalist>

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

Page 68: Advanced html5 for android application development in phonegap

<keygen> Element

• The purpose of the <keygen> element is to provide a secure way to authenticate users.

• The <keygen> element is a key-pair generator. When a form is submitted, two keys are generated, one private and one public.

• The private key is stored on the client, and the public key is sent to the server.

• The public key could be used to generate a client certificate to authenticate the user in the future.

Page 69: Advanced html5 for android application development in phonegap

<keygen> Element

<!DOCTYPE html>

<html>

<body> <form action="demo_keygen.asp" method="get">

Username: <input type="text" name="usr_name" />

Encryption: <keygen name="security" />

<input type="submit" />

</form>

</body>

</html>

Page 70: Advanced html5 for android application development in phonegap

<output> Element

• The <output> element is used for different types of output, like calculations or script output:

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0

<input type="range" name="a" value="50" />100

+<input type="number" name="b" value="50" />

=<output name="x" for="a b"></output>

</form>

Page 71: Advanced html5 for android application development in phonegap

HTML5 Form Attributes

Page 72: Advanced html5 for android application development in phonegap

HTML5 New Form Attributes

New form attributes: autocomplete Novalidate

New input attributes: autocomplete autofocus form form overrides (formaction, formenctype, formmethod, formnovalidate, formtarget) height and width list min, max and step multiple pattern (regexp) placeholder required

Page 73: Advanced html5 for android application development in phonegap

Browser support attributes

Attribute IE Firefox Opera Chrome Safari

autocomplete 8.0 3.5 9.5 3.0 4.0

autofocus No 4.0 10.0 3.0 4.0

form No 4.0 9.5 10.0 No

form overrides No 4.0 10.5 10.0 No

height and width 8.0 3.5 9.5 3.0 4.0

list No 4.0 9.5 No No

min, max and step No No 9.5 3.0 No

multiple No 3.5 11.0 3.0 4.0

novalidate No 4.0 11.0 10.0 No

pattern No 4.0 9.5 3.0 No

placeholder No 4.0 11.0 3.0 3.0

required No 4.0 9.5 3.0 No

Page 74: Advanced html5 for android application development in phonegap

autocomplete Attribute

<!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get" autocomplete="on"> First name:<input type="text" name="fname" /><br /> E-mail: <input type="email" name="email" /><br /> <input type="submit" /> </form> <p>Fill in and submit the form, then reload the page, start to fill in the form again -

and see how autocomplete works.</p> <p>Then, try to set autocomplete to "off".</p> </body> </html>

Page 75: Advanced html5 for android application development in phonegap

autofocus Attribute

The autofocus attribute specifies that a field should automatically get focus when a page is loaded.

<!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get"> User name: <input type="text" name="user_name" autofocus="autofocus" /> <input type="submit" /> </form> </body> </html>

Page 76: Advanced html5 for android application development in phonegap

form Attribute

The form attribute specifies one or more forms the input field belongs to. • Note: The form attribute works with all <input> types. • The form attribute must refer to the id of the form it belongs to: <!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get" id="user_form"> First name:<input type="text" name="fname" /> <input type="submit" /> </form> <p>The input field below is outside the form element, but still part of the form.</p> Last name: <input type="text" name="lname" form="user_form" /> </body> </html>

Page 77: Advanced html5 for android application development in phonegap

Form Override Attributes

Form Override Attributes The form override attributes allow you to override some

of the attributes set for the form element. The form override attributes are: • formaction - Overrides the form action attribute • formenctype - Overrides the form enctype attribute • formmethod - Overrides the form method attribute • formnovalidate - Overrides the form novalidate

attribute • formtarget - Overrides the form target attribute

Page 78: Advanced html5 for android application development in phonegap

Form Override Attributes

• Note: The form override attributes works with the following <input> types: submit and image.

<!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get" id="user_form"> E-mail: <input type="email" name="userid" /><br /> <input type="submit" value="Submit" /><br /> <input type="submit" formaction="demo_admin.asp" value="Submit as admin" /><br /> <input type="submit" formnovalidate="true" value="Submit without validation" /><br /> </form> </body> </html> Note: These attributes are helpful for creating different submit buttons.

Page 79: Advanced html5 for android application development in phonegap

height and width Attributes

• The height and width attributes specifies the height and width of the image used for the input type image.

• Note: The height and width attributes only works with <input> type: image.

<!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get"> User name: <input type="text" name="user_name" /><br /> <input type="image" src="img_submit.gif" width="24" height="24" /> </form> </body> </html>

Page 80: Advanced html5 for android application development in phonegap

list Attribute

• The list attribute specifies a datalist for an input field. A datalist is a list of options for an input field. • Note: The list attribute works with the following <input> types: text, search, url, telephone, email, date pickers,

number, range, and color. <!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get"> Webpage: <input type="url" list="url_list" name="link" /> <datalist id="url_list"> <option label="W3Schools" value="http://www.w3schools.com" /> <option label="Google" value="http://www.google.com" /> <option label="Microsoft" value="http://www.microsoft.com" /> </datalist> <input type="submit" /> </form> </body> </html>

Page 81: Advanced html5 for android application development in phonegap

min, max and step Attributes

• The min, max and step attributes are used to specify restrictions for input types containing numbers or dates.

• The max attribute specifies the maximum value allowed for the input field. • The min attribute specifies the minimum value allowed for the input field. • The step attribute specifies the legal number intervals for the input field (if

step="3", legal numbers could be -3,0,3,6, etc). • Note: The min, max, and step attributes works with the following <input>

types: date pickers, number, and range. • The example below shows a numeric field that accepts values between 0

and 10, with a step of 3 (legal numbers are 0, 3, 6 and 9): <form action="demo_form.asp" method="get"> Points: <input type="number" name="points" min="0" max="10" step="3"/> <input type="submit" /> </form>

Page 82: Advanced html5 for android application development in phonegap

multiple Attribute

• The multiple attribute specifies that multiple values can be selected for an input field. • Note: The multiple attribute works with the following <input> types: email, and file. <!DOCTYPE html> <html> <body> <form action="demo_form.asp" method="get"> Select images: <input type="file" name="img" multiple="multiple" /> <input type="submit" /> </form> <p>Try selecting more than one file when browsing for files.</p> </body> </html>

Page 83: Advanced html5 for android application development in phonegap

novalidate Attribute

• The novalidate attribute specifies that the form or input field should not be validated when submitted.

• If this attribute is present the form will not validate form input. • Note: The novalidate attribute works with: <form> and the following

<input> types: text, search, url, telephone, email, password, date pickers, range, and color.

<!DOCTYPE html> <html>

<body> <form action="demo_form.asp" novalidate="novalidate">

E-mail: <input type="email" name="user_email" /> <input type="submit" />

</form>

</body>

</html>

Page 84: Advanced html5 for android application development in phonegap

pattern Attribute

• The pattern attribute specifies a pattern used to validate an input field.

• The pattern is a regular expression. • Note: The pattern attribute works with the following <input> types:

text, search, url, telephone, email, and password • The example below shows a text field that can only contain three

letters (no numbers or special characters): <form action="demo_form.asp" method="get"> Country code: <input type="text" name="country_code" pattern="[A-

z]{3}" title="Three letter country code" /> <input type="submit" /> </form>

Page 85: Advanced html5 for android application development in phonegap

placeholder Attribute

• The placeholder attribute provides a hint that describes the expected value of an input field.

• Note: The placeholder attribute works with the following <input> types: text, search, url, telephone, email, and password

<!DOCTYPE html> <html> <body>

<form action="demo_form.asp" method="get"> <input type="search" name="user_search" placeholder="Emp ID" /> <input type="submit" /> </form>

</body> </html>

Page 86: Advanced html5 for android application development in phonegap

required Attribute

• The required attribute specifies that an input field must be filled out before submitting.

• Note: The required attribute works with the following <input> types: text, search, url, telephone, email, password, date pickers, number, checkbox, radio, and file.

<form action="demo_form.asp" method="get"> Name: <input type="text" name="usr_name"

required="required" /> <input type="submit" /> </form>

Page 87: Advanced html5 for android application development in phonegap

HTML5 Reference

Page 88: Advanced html5 for android application development in phonegap

HTML5 Tags

• HTML5 improves interoperability and reduces development costs by making precise rules on how to handle all HTML elements, and how to recover from errors.

• Some of the new features in HTML5 are functions for embedding audio, video, graphics, client-side data storage, and interactive documents.

• HTML5 also contains new elements like <nav>, <header>, <footer>, and <figure>.

• The HTML5 working group includes AOL, Apple, Google, IBM, Microsoft, Mozilla, Nokia, Opera, and many hundreds of other vendors.

• Note: HTML5 is not a W3C recommendation yet!

Page 89: Advanced html5 for android application development in phonegap

W3C HTML Activities

• HTML is the universal markup language for the Web

Page 90: Advanced html5 for android application development in phonegap

HTML Versions

HTML 2.0 • HTML 2.0 was developed by the Internet Engineering Task Force HTML

Working Group in 1996. • HTML 2.0 is an outdated version of HTML. For a Web developer there is no

need to study the HTML 2.0 standard. HTML 3.2 • HTML 3.2 became a W3C Recommendation 14. January 1997. HTML 3.2

added new features such as fonts, tables, applets, superscripts, subscripts and more, to the existing HTML 2.0 standard.

• One of the elements added to the HTML 3.2 standard, was the <font> tag. This tag introduced unnecessary complexity to the important task of separating HTML content (text) from its presentation (style). The <font> tag became deprecated in HTML 4.0.

HTML 4.0 • HTML 4.0 became a W3C Recommendation 18. December 1997. A second

release was issued on 24. April 1998 with only some editorial corrections.

Page 91: Advanced html5 for android application development in phonegap

HTML Versions

The most important feature of HTML 4.0 was the introduction of style sheets (CSS).

HTML 4.01 • HTML 4.01 became a W3C Recommendation 24.

December 1999. • HTML 4.01 was a minor update of corrections and bug-

fixes from HTML 4.0. • XHTML 1.0 • XHTML 1.0 reformulates HTML 4.01 in XML. • XHTML 1.0 became a W3C Recommendation 20.

January 2000.

Page 92: Advanced html5 for android application development in phonegap

HTML Versions

HTML 5

• On January 22nd, 2008, W3C published a working draft for HTML 5.

Specification Recommendation

HTML 3.2 14. January 1997

HTML 4.0 24. April 1998

HTML 4.01 24. December 1999

HTML 5 19. October 2010 (latest draft)

Page 93: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<!--...--> Defines a comment

<!DOCTYPE> Defines the document type

<a> Defines a hyperlink

<abbr> Defines an abbreviation

<acronym> Not supported in HTML5

<address> Defines contact information for the author/owner of a document/article

<applet> Not supported in HTML5

<area> Defines an area inside an image-map

<article>New Defines an article

<aside>New Defines content aside from the page content

<audio>New Defines sound content

Page 94: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<b> Defines bold text

<base> Specifies the base URL/target for all relative URLs in a document

<basefont> Not supported in HTML5

<bdi>New Isolates a part of text that might be formatted in a different direction from other text outside it

<bdo> Overrides the current text direction

<big> Not supported in HTML5

<blockquote> Defines a section that is quoted from another source

<body> Defines the document's body

<br> Defines a single line break

<button> Defines a clickable button

<canvas>New Used to draw graphics, on the fly, via scripting (usually JavaScript)

<caption> Defines a table caption

<center> Not supported in HTML5

Page 95: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<cite> Defines the title of a work

<code> Defines a piece of computer code

<col> Specifies column properties for each column within a <colgroup> element

<colgroup> Specifies a group of one or more columns in a table for formatting

<command>New Defines a command button that a user can invoke

<datalist>New Specifies a list of pre-defined options for input controls

<dd> Defines a description of an item in a definition list

<del> Defines a text that has been deleted from a document

<details>New Defines additional details that the user can view or hide

<dfn> Defines a definition term

<dir> Not supported in HTML5

<div> Defines a section in a document

<dl> Defines a definition list

Page 96: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<dt> Defines a term (an item) in a definition list

<em> Defines emphasized text

<embed>New Defines a container for an external application or interactive content (a plug-in)

<fieldset> Groups related elements in a form

<figcaption>New Defines a caption for a <figure> element

<figure>New Specifies self-contained content

<font> Not supported in HTML5

<footer>New Defines a footer for a document or section

<form> Defines an HTML form for user input

<frame> Not supported in HTML5

<frameset> Not supported in HTML5

<h1> to <h6> Defines HTML headings

<head> Defines information about the document

Page 97: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<header>New Specifies an introduction, or a group of navigation elements for a document

<hgroup>New Groups a set of <h1> to <h6> elements when a heading has multiple levels

<hr> Defines a thematic change in the content

<html> Defines the root of an HTML document

<i> Defines a part of text in an alternate voice or mood

<iframe> Defines an inline frame

<img> Defines an image

<input> Defines an input control

<ins> Defines a text that has been inserted into a document

<keygen>New Defines a key-pair generator field (for forms)

<kbd> Defines keyboard input

<label> Defines a label for an input element

Page 98: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<legend> Defines a caption for a <fieldset>, <figure>, or <details> element

<li> Defines a list item

<link> Defines the relationship between a document and an external resource (most used to link to style sheets)

<map> Defines a client-side image-map

<mark>New Defines marked/highlighted text

<menu> Defines a list/menu of commands

<meta> Defines metadata about an HTML document

<meter>New Defines a scalar measurement within a known range (a gauge)

<nav>New Defines navigation links

<noframes> Not supported in HTML5

<noscript> Defines an alternate content for users that do not support client-side scripts

<object> Defines an embedded object

Page 99: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<ol> Defines an ordered list

<optgroup> Defines a group of related options in a drop-down list

<option> Defines an option in a drop-down list

<output>New Defines the result of a calculation

<p> Defines a paragraph

<param> Defines a parameter for an object

<pre> Defines preformatted text

<progress>New Represents the progress of a task

<q> Defines a short quotation

<rp>New Defines what to show in browsers that do not support ruby annotations

<rt>New Defines an explanation/pronunciation of characters (for East Asian typography)

<ruby>New Defines a ruby annotation (for East Asian typography)

Page 100: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<ruby>New Defines a ruby annotation (for East Asian typography)

<s> Defines text that is no longer correct

<samp> Defines sample output from a computer program

<script> Defines a client-side script

<section>New Defines a section in a document

<select> Defines a drop-down list

<small> Defines smaller text

<source>New Defines multiple media resources for media elements (<video> and <audio>)

<span> Defines a section in a document

<strike> Not supported in HTML5

<strong> Defines important text

<style> Defines style information for a document

Page 101: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<sub> Defines subscripted text

<summary>New Defines a visible heading for a <details> element

<sup> Defines superscripted text

<table> Defines a table

<tbody> Groups the body content in a table

<td> Defines a cell in a table

<textarea> Defines a multiline input control (text area)

<tfoot> Groups the footer content in a table

<th> Defines a header cell in a table

<thead> Groups the header content in a table

<sub> Defines subscripted text

<summary>New Defines a visible heading for a <details> element

Page 102: Advanced html5 for android application development in phonegap

New tags in HTML5 Tag Description

<time>New Defines a date/time

<title> Defines a title for the document

<tr> Defines a row in a table

<track>New Defines text tracks for media elements (<video> and <audio>)

<tt> Not supported in HTML5

<u> Not supported in HTML5

<ul> Defines an unordered list

<var> Defines a variable

<video>New Defines a video or movie

<wbr>New Defines a possible line-break

<time>New Defines a date/time

<title> Defines a title for the document

Page 103: Advanced html5 for android application development in phonegap

HTML5 Global Attributes

• The global attributes are supported by all HTML 5 elements (with a few exceptions).

• New global attributes in HTML5.

Attribute Value Description

accesskey character Specifies a shortcut key to access an element

class classname Refers to a class specified in a style sheet

contenteditableNew

true false inherit

Specifies whether a user can edit the content of an element or not

Page 104: Advanced html5 for android application development in phonegap

contextmenuNew menu_id Specifies a context menu for an element. The value must be the id of a <menu> element

dir ltr rtl auto

Specifies the text direction for the content in an element

draggableNew true false auto

Specifies whether a user is allowed to drag an element or not

dropzoneNew copy move link

Specifies what happens when dragged items/data is dropped in the element

hiddenNew hidden Specifies that an element should be hidden

id id Specifies a unique id for an element

lang language_code Specifies the language of the element's content

spellcheckNew true false

Specifies if the element must have its spelling and grammar checked

style style_definitions Specifies an inline style for an element

tabindex number Specifies the tab order of an element

title text Specifies extra information about an element

Page 105: Advanced html5 for android application development in phonegap

HTML5 Event Attributes

• HTML 4 added the ability to let events trigger actions in a browser, like starting a JavaScript when a user clicks on an element.

• New event attributes in HTML5.

Attribute Value Description

nafterprintNew script Script to be run after the document is printed

onbeforeprintNew script Script to be run before the document is printed

onbeforeonloadNew script Script to be run before the document loads

onblur script Script to be run when the window loses focus

onerrorNew script Script to be run when an error occur

onfocus script Script to be run when the window gets focus

onhaschangeNew script Script to be run when the document has changed

Page 106: Advanced html5 for android application development in phonegap

HTML5 Event Attributes Attribute Value Description

onload script Script to be run when the document loads

onmessageNew script Script to be run when the message is triggered

onofflineNew script Script to be run when the document goes offline

ononlineNew script Script to be run when the document comes online

onpagehideNew script Script to be run when the window is hidden

onpageshowNew script Script to be run when the window becomes visible

onpopstateNew script Script to be run when the window's history changes

onredoNew script Script to be run when the document performs a redo

onresizeNew script Script to be run when the window is resized

onstorageNew script Script to be run when when a Web Storage area is updated

onundoNew script Script to be run when the document performs an undo

onunloadNew script Script to be run when the user leaves the document

Page 107: Advanced html5 for android application development in phonegap

Form Events Attribute Value Description

onblur script Script to be run when an element loses focus

onchange script Script to be run when an element changes

oncontextmenuNew script Script to be run when a context menu is triggered

onfocus script Script to be run when an element gets focus

onformchangeNew script Script to be run when a form changes

onforminputNew script Script to be run when a form gets user input

oninputNew script Script to be run when an element gets user input

oninvalidNew script Script to be run when an element is invalid

onreset script Script to be run when a form is reset Not supported in HTML5

onselect script Script to be run when an element is selected

onsubmit script Script to be run when a form is submitted

Page 108: Advanced html5 for android application development in phonegap

Keyboard Events

Attribute Value Description

onkeydown script Script to be run when a key is pressed down

onkeypress script Script to be run when a key is pressed and released

onkeyup script Script to be run when a key is released

Events triggered by a keyboard (applies to all HTML5 elements):

Page 109: Advanced html5 for android application development in phonegap

Mouse Events Attribute Value Description

onabort script Script to be run on abort

oncanplayNew script Script to be run when a file is ready to start playing (when it has buffered enough to begin)

oncanplaythroughNew script Script to be run when a file can be played all the way to the end without pausing for buffering

ondurationchangeNew script Script to be run when the length of the media changes

onemptiedNew script Script to be run when something bad happens and the file is suddenly unavailable (like unexpectedly disconnects)

onendedNew script Script to be run when the media has reach the end (a useful event for messages like "thanks for listening")

onerrorNew script Script to be run when an error occurs when the file is being loaded

onloadeddataNew script Script to be run when media data is loaded

onloadedmetadataNew script Script to be run when meta data (like dimensions and duration) are loaded

Page 110: Advanced html5 for android application development in phonegap

Mouse Events Attribute Value Description

onloadstartNew script Script to be run just as the file begins to load before anything is actually loaded

onpauseNew script Script to be run when the media is paused either by the user or programmatically

onplayNew script Script to be run when the media is ready to start playing

onplayingNew script Script to be run when the media actually has started playing

onprogressNew script Script to be run when the browser is in the process of getting the media data

onratechangeNew script Script to be run each time the playback rate changes (like when a user switches to a slow motion or fast forward mode)

onreadystatechangeNew script Script to be run each time the ready state changes (the ready state tracks the state of the media data)

onseekedNew script Script to be run when the seeking attribute is set to false indicating that seeking has ended

Page 111: Advanced html5 for android application development in phonegap

Mouse Events Attribute Value Description

onseekingNew script Script to be run when the seeking attribute is set to true indicating that seeking is active

onstalledNew script Script to be run when the browser is unable to fetch the media data for whatever reason

onsuspendNew script Script to be run when fetching the media data is stopped before it is completely loaded for whatever reason

ontimeupdateNew script Script to be run when the playing position has changed (like when the user fast forwards to a different point in the media)

onvolumechangeNew

script Script to be run each time the volume is changed which (includes setting the volume to "mute")

onwaitingNew script Script to be run when the media has paused but is expected to resume (like when the media pauses to buffer more data)

onseekingNew script Script to be run when the seeking attribute is set to true indicating that seeking is active

onstalledNew script Script to be run when the browser is unable to fetch the media data for whatever reason

Page 112: Advanced html5 for android application development in phonegap

HTML5 canvas.getContext("2d") reference

Context

• The canvas element has no drawing abilities of its own.

• A canvas is a rectangular area, where you can control every pixel using JavaScript.

• HTML5 has a built-in object for the canvas element, the getContext("2d") object.

• The getContext("2d") object has methods to draw lines, boxes, circles, and more.

Page 113: Advanced html5 for android application development in phonegap

Colors and Styles Attribute Value Description

fillStyle color/style The fill-color of the drawing, black is default

strokeStyle color/style The stroke-color of the drawing, black is default

lineWidth number The width of the drawing stroke, 1 is default

lineCap butt round square

The style of the ending of the line, butt is default

lineJoin bevel round miter

The style of the corners of the line, miter is default

miterLimit number The limit size of the corners in a line, default is 10

shadowColor color The color of the shadow, black is default

shadowOffsetX number The horizontal distance of the shadow, 0 is default

shadowOffsetY number The vertical distance of the shadow, 0 is default

shadowBlur number The size of the blurring effect, 0 is default

Page 114: Advanced html5 for android application development in phonegap

Colors and Styles Method Description

createPattern(obj,pattern) Creates a pattern from an image to be used by the fillStyle or strokeStyle attributes

createLinearGradient(x0,y0,z1,y1)

Creates a gradient object. Use this object as a value to the strokeStyle or fillStyle attributes

createRadialGradient(x0,y0,r0,x1,y1,r1)

Creates a gradient object as a circle. Use this object as a value to the strokeStyle or fillStyle attributes

addColorStop(position,color) This is a method of the gradient objects above. Specifies the gradient's position and color

drawCustomFocusRing(element)

drawSystemFocusRing(element)

Page 115: Advanced html5 for android application development in phonegap

Path, Curve, Circle, and Rectangle

Method Description

fill() Fills the current path with the selected color, black is default

stroke() Creates a stroke/path described with the specified path methods

clip() Creates an area in the canvas, and this area is the only visible area in the canvas

quadraticCurveTo(cpx,cpy,x,y) Creates a quadratic Bezier curve from the current point in the path to the specified path

bezierCurveTo(cpx,cpy,cpx,cpy,x,y) Creates a cubic Bezier curve from the current point in the path to the specified path

arc(x,y,r,sAngle,eAngle,aClockwise) Creates a circle, or parts of a circle

arcTo(x1,y1,x2,y2,radius) Creates an arc between two points

isPointInPath(x,y) Returns a Boolean value, true if the specified point is in the path, otherwise false

Page 116: Advanced html5 for android application development in phonegap

Path, Curve, Circle, and Rectangle

Method Description

fillRect(x,y,w,h) Draws a filled rectangle using the color/style of the fillStyle attribute

strokeRect(x,y,w,h) Draws the lines of a rectangle using the color/style of the strokeStyle attribute

clearRect(x,y,w,h) Clears a rectangle area. All pixels inside this area will be erased

beginPath() Starts a new path, or clears the current path

moveTo(x,y) Moves the path to the specified point, without creating a line

closePath() Creates a line (path) from the last point in the path, to the first point. Completes the path

lineTo(x,y) Creates a line from the last point in the path to the given point

rect(x,y,w,h) Creates a rectangle

Page 118: Advanced html5 for android application development in phonegap

Text

Attribute Value Description

font fontproperties Specifies font properties used for writing on the canvas

textAlign

start end left right center

The alignment of the text, "start" is default

textBaseline

alphabetic bottom hanging ideographic middle top

The vertical alignment of the text, "alphabetic" is default

Page 119: Advanced html5 for android application development in phonegap

Text

Method Description

fillText(text,x,y,maxWidth) Draws text on the canvas, and fills it with the color set by the fillStyle attribute

strokeText(text,x,y,maxWidth)

Draws text on the canvas, without filling, using the color set by the strokeStyle attribute.

measureText(text).width Measures the given text string, returns the result in pixels

Page 120: Advanced html5 for android application development in phonegap

Images and Pixel Manipulation

Attribute Value Description

width number Specifies the width of the imagedata object

height number Specifies the height of the imagedata object

data array An array containing the rgba values of all pixels in an imagedata object

Method Description

drawImage() Use a picture when drawing onto the canvas

createImageData() Creates a blank imagedata object

getImageData(x,y,w,h) Creates a new imagedata object, containing data from the canvas

putImageData(imgdat,dx,dy,x,y,w,h) Draws imagedata onto th canvas

Page 121: Advanced html5 for android application development in phonegap

Compositing

Attribute Value Description

globalAlpha number Specifies the transparency of the drawings

globalCompositeOperation

source-atop source-in source-out source-over destination-atop destination-in destination-out destination-over lighter copy xor vendorName-operationName

Specifies how shapes and drawings are positioned onto the canvas, source-over is default

Page 122: Advanced html5 for android application development in phonegap

HTML Elements and Valid Doctypes

• HTML5/HTML 4.01/XHTML Elements and Valid DTDs

• The table below lists all HTML5/HTML 4.01/XHTML elements, and shows what Doctype (DTD) each element appears in.

Page 124: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<big> No Yes Yes Yes Yes

<blockquote>

Yes Yes Yes Yes Yes

<body> Yes Yes Yes Yes Yes

<br> Yes Yes Yes Yes Yes

<button> Yes Yes Yes Yes Yes

<canvas> Yes No No No No

<caption> Yes Yes Yes Yes Yes

<center> No Yes No Yes No

<cite> Yes Yes Yes Yes Yes

<code> Yes Yes Yes Yes Yes

<col> Yes Yes Yes Yes No

<colgroup> Yes Yes Yes Yes No

<command> Yes No No No No

<datalist> Yes No No No No

Page 125: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<dd> Yes Yes Yes Yes Yes

<del> Yes Yes Yes Yes No

<details> Yes No No No No

<dfn> Yes Yes Yes Yes Yes

<dir> No Yes No Yes No

<div> Yes Yes Yes Yes Yes

<dl> Yes Yes Yes Yes Yes

<dt> Yes Yes Yes Yes Yes

<em> Yes Yes Yes Yes Yes

<embed> Yes No No No No

<fieldset> Yes Yes Yes Yes Yes

<figcaption> Yes No No No No

<figure> Yes No No No No

<font> No Yes No Yes No

Page 126: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<footer> Yes No No No No

<form> Yes Yes Yes Yes Yes

<frame> No No No Yes No

<frameset> No No No Yes No

<h1> to <h6>

Yes Yes Yes Yes Yes

<head> Yes Yes Yes Yes Yes

<header> Yes No No No No

<hgroup> Yes No No No No

<hr> Yes Yes Yes Yes Yes

<html> Yes Yes Yes Yes Yes

<i> Yes Yes Yes Yes Yes

<iframe> Yes Yes No Yes No

<img> Yes Yes Yes Yes Yes

<input> Yes Yes Yes Yes Yes

Page 127: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<ins> Yes Yes Yes Yes No

<keygen> Yes No No No No

<kbd> Yes Yes Yes Yes Yes

<label> Yes Yes Yes Yes Yes

<legend> Yes Yes Yes Yes Yes

<li> Yes Yes Yes Yes Yes

<link> Yes Yes Yes Yes Yes

<map> Yes Yes Yes Yes No

<mark> Yes No No No No

<menu> Yes Yes No Yes No

<meta> Yes Yes Yes Yes Yes

<meter> Yes No No No No

<nav> Yes No No No No

<noframes> No Yes No Yes No

Page 128: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<noscript> Yes Yes Yes Yes Yes

<object> Yes Yes Yes Yes Yes

<ol> Yes Yes Yes Yes Yes

<optgroup> Yes Yes Yes Yes Yes

<option> Yes Yes Yes Yes Yes

<output> Yes No No No No

<p> Yes Yes Yes Yes Yes

<param> Yes Yes Yes Yes Yes

<pre> Yes Yes Yes Yes Yes

<progress> Yes No No No No

<q> Yes Yes Yes Yes Yes

<rp> Yes No No No No

<rt> Yes No No No No

<ruby> Yes No No No No

Page 129: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<s> Yes Yes No Yes No

<samp> Yes Yes Yes Yes Yes

<script> Yes Yes Yes Yes Yes

<section> Yes No No No No

<select> Yes Yes Yes Yes Yes

<small> Yes Yes Yes Yes Yes

<source> Yes No No No No

<span> Yes Yes Yes Yes Yes

<strike> No Yes No Yes No

<strong> Yes Yes Yes Yes Yes

<style> Yes Yes Yes Yes Yes

<sub> Yes Yes Yes Yes Yes

<summary> Yes No No No No

<sup> Yes Yes Yes Yes Yes

Page 130: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<table> Yes Yes Yes Yes Yes

<tbody> Yes Yes Yes Yes No

<td> Yes Yes Yes Yes Yes

<textarea> Yes Yes Yes Yes Yes

<tfoot> Yes Yes Yes Yes No

<th> Yes Yes Yes Yes Yes

<thead> Yes Yes Yes Yes No

<time> Yes No No No No

<title> Yes Yes Yes Yes Yes

<tr> Yes Yes Yes Yes Yes

<track> Yes No No No No

<tt> No Yes Yes Yes Yes

<u> No Yes No Yes No

<ul> Yes Yes Yes Yes Yes

Page 131: Advanced html5 for android application development in phonegap

Tag HTML5

HTML 4.01 / XHTML 1.0

XHTML 1.1 Transitional Strict Frameset

<var> Yes Yes Yes Yes Yes

<video> Yes No No No No

<wbr> Yes No No No No

Page 132: Advanced html5 for android application development in phonegap

HTML5 Day 5

Data Storage

HTML5 Web Workers

HTML5 Messaging APIs

HTML5 Web Sockets

HTML5 Offline Web Applications

Hands-on exercises

Page 133: Advanced html5 for android application development in phonegap

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

Page 134: Advanced html5 for android application development in phonegap

Data Storage

• Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.

• Local storage is per domain. All pages, from one domain, can store and access the same data.

• HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome following drawbacks :-

Page 135: Advanced html5 for android application development in phonegap

Data Storage

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

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

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

Page 136: Advanced html5 for android application development in phonegap

Data Storage

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

Page 137: Advanced html5 for android application development in phonegap

Data Storage

HTML local storage provides two objects for storing data on the client:

• window.localStorage - stores data with no expiration date

• code.sessionStorage - stores data for one session (data is lost when the tab is closed)

Page 138: Advanced html5 for android application development in phonegap

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.

• HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage,

Page 139: Advanced html5 for android application development in phonegap

Session Storage <!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>

Page 140: Advanced html5 for android application development in phonegap

Local Storage:

• The Local Storage is designed for storage that spans multiple windows, and lasts beyond the current session.

• Specially in 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.

Page 141: Advanced html5 for android application development in phonegap

Local Storage:

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

Page 142: Advanced html5 for android application development in phonegap

Local Storage: <!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>

Page 143: Advanced html5 for android application development in phonegap

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.

Page 144: Advanced html5 for android application development in phonegap

Delete Web Storage: • 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.

Page 145: Advanced html5 for android application development in phonegap

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

Page 146: Advanced html5 for android application development in phonegap

HTML5 Web Workers

Page 147: Advanced html5 for android application development in phonegap

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

Page 148: Advanced html5 for android application development in phonegap

HTML5 Web Workers

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

Page 149: Advanced html5 for android application development in phonegap

HTML5 Web Workers

<!DOCTYPE HTML> <html> <head> <title>Big for loop</title> <script> function bigLoop(){ for (var i = 0; i <= 10000000000; i += 1){ var j = i; } 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>

Page 150: Advanced html5 for android application development in phonegap

What is Web Workers?

• The situation explained above can be handled using Web Workers who will do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads.

Page 151: Advanced html5 for android application development in phonegap

What is Web Workers?

• Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.

Page 152: Advanced html5 for android application development in phonegap

What is Web Workers?

• Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers.

• For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image.

Page 153: Advanced html5 for android application development in phonegap

What is Web Workers?

• A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page.

• You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Page 154: Advanced html5 for android application development in phonegap

Check Web Worker Support

if(typeof(Worker) !== "undefined") { // Yes! Web worker support! // Some code..... } else { // Sorry! No Web Worker support.. }

Page 155: Advanced html5 for android application development in phonegap

How Web Workers Work?

Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute.

This code sets event listeners and communicates with the script that spawned it from the main page. Following is the simple syntax:

var worker = new Worker('bigLoop.js');

Page 156: Advanced html5 for android application development in phonegap

How Web Workers Work?

If the specified javascript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously.

If the path to your worker returns an 404, the worker will fail silently.

Page 157: Advanced html5 for android application development in phonegap

How Web Workers Work?

If your application has multiple supporting javascript files, you can import themimportScripts() method which takes file name(s) as argument separated by comma as follows:

importScripts("helper.js", "anotherHelper.js");

Page 158: Advanced html5 for android application development in phonegap

How Web Workers Work?

Once the Web Worker is spawned, communication between web worker and its parent page is done using the postMessage() method.

Page 159: Advanced html5 for android application development in phonegap

How Web Workers Work?

Message passed by Web Worker is accessed using onmessage event in the main page.

Page 160: Advanced html5 for android application development in phonegap

How Web Workers Work?

<!DOCTYPE HTML> <html> <head> <title>Big for loop</title> <script> var worker = new Worker('bigLoop.js'); worker.onmessage = function (event) { alert("Completed " + event.data + "iterations" ); }; function sayHello(){ alert("Hello sir...." ); } </script> </head> <body> <input type="button" onclick="sayHello();" value="Say Hello"/> </body> </html>

Page 161: Advanced html5 for android application development in phonegap

How Web Workers Work?

bigLoop.js file is below -

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

var j = i;

}

postMessage(j);

Page 162: Advanced html5 for android application development in phonegap

Stopping Web Workers:

Web Workers don't stop by themselves but the page that started them can stop them by calling terminate() method.

worker.terminate();

Page 163: Advanced html5 for android application development in phonegap

Handling Errors:

<!DOCTYPE HTML>

<html>

<head>

<title>Big for loop</title>

<script>

var worker = new Worker('bigLoop.js');

worker.onmessage = function (event) {

alert("Completed " + event.data + "iterations" );

};

worker.onerror = function (event) {

console.log(event.message, event);

};

function sayHello(){

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

}

</script>

</head>

<body>

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

</body>

</html>

Page 164: Advanced html5 for android application development in phonegap

HTML5 - WebSockets

Page 165: Advanced html5 for android application development in phonegap

Web Sockets

• Web Sockets 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.

Page 166: Advanced html5 for android application development in phonegap

Web Sockets

• 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 onmessageevent handler.

Page 167: Advanced html5 for android application development in phonegap

Web Sockets

• Following is the API which creates a new WebSocket object

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

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.

Page 168: Advanced html5 for android application development in phonegap

WebSocket Attributes 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. 2.A value of 1 indicates that the connection is established and communication is possible. 3.A value of 2 indicates that the connection is going through the closing handshake. 4.A value of 3 indicates that the connection has been closed or could not be opened.

Socket.bufferedAmount

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

Page 169: Advanced html5 for android application development in phonegap

WebSocket Events

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.

Page 170: Advanced html5 for android application development in phonegap

WebSocket Methods

Method Description

Socket.send() The send(data) method transmits data using the connection.

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

Page 171: Advanced html5 for android application development in phonegap

Web Sockets <!DOCTYPE HTML> <html> <head> <script type="text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket is supported by your Browser!"); // Let us open a web socket var ws = new WebSocket("ws://localhost:80"); 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!"); } } </script> </head> <body> <div id="sse"> <a href="javascript:WebSocketTest()">Run WebSocket</a> </div> </body> </html>

Page 172: Advanced html5 for android application development in phonegap

HTML5 Messaging APIs

Page 173: Advanced html5 for android application development in phonegap

HTML5 Status Message

• When a browser requests a service from a web server, an error might occur.

• This is a list of HTTP status messages that might be returned:

Page 174: Advanced html5 for android application development in phonegap

Information

Message: Description:

100 Continue The server has received the request headers, and the client should proceed to send the request body

101 Switching Protocols The requester has asked the server to switch protocols

103 Checkpoint Used in the resumable requests proposal to resume aborted PUT or POST requests

Page 175: Advanced html5 for android application development in phonegap

Successful

Message: Description:

200 OK The request is OK (this is the standard response for successful HTTP requests)

201 Created The request has been fulfilled, and a new resource is created

202 Accepted The request has been accepted for processing, but the processing has not been completed

203 Non-Authoritative Information The request has been successfully processed, but is returning information that may be from another source

204 No Content The request has been successfully processed, but is not returning any content

205 Reset Content The request has been successfully processed, but is not returning any content, and requires that the requester reset the document view

206 Partial Content The server is delivering only part of the resource due to a range header sent by the client

Page 176: Advanced html5 for android application development in phonegap

Redirection

Message: Description:

300 Multiple Choices A link list. The user can select a link and go to that location. Maximum five addresses

301 Moved Permanently The requested page has moved to a new URL

302 Found The requested page has moved temporarily to a new URL

303 See Other The requested page can be found under a different URL

304 Not Modified Indicates the requested page has not been modified since last requested

306 Switch Proxy No longer used

307 Temporary Redirect The requested page has moved temporarily to a new URL

308 Resume Incomplete Used in the resumable requests proposal to resume aborted PUT or POST requests

Page 177: Advanced html5 for android application development in phonegap

Client Error

Message: Description:

400 Bad Request The request cannot be fulfilled due to bad syntax

401 Unauthorized The request was a legal request, but the server is refusing to respond to it. For use when authentication is possible but has failed or not yet been provided

402 Payment Required Reserved for future use

403 Forbidden The request was a legal request, but the server is refusing to respond to it

404 Not Found The requested page could not be found but may be available again in the future

405 Method Not Allowed A request was made of a page using a request method not supported by that page

Page 178: Advanced html5 for android application development in phonegap

Server Error

Message: Description:

500 Internal Server Error A generic error message, given when no more specific message is suitable

501 Not Implemented The server either does not recognize the request method, or it lacks the ability to fulfill the request

502 Bad Gateway The server was acting as a gateway or proxy and received an invalid response from the upstream server

503 Service Unavailable The server is currently unavailable (overloaded or down)

504 Gateway Timeout The server was acting as a gateway or proxy and did not receive a timely response from the upstream server

Page 179: Advanced html5 for android application development in phonegap

HTML5 Server-Sent Events

• Server-Sent Events allow a web page to get updates from a server.

• This was also possible before, but the web page would have to ask if any updates were available.

• With server-sent events, the updates come automatically.

Page 180: Advanced html5 for android application development in phonegap

Receive Server-Sent Event Notifications

var source = new EventSource("demo_sse.php");

source.onmessage = function(event)

{

document.getElementById("result").innerHTML += event.data + "<br>";

};

Page 181: Advanced html5 for android application development in phonegap

Receive Server-Sent Event Notifications

<!DOCTYPE html> <html> <body> <h1>Getting server updates</h1> <div id="result"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html>

Page 182: Advanced html5 for android application development in phonegap

Server-Side Code

• you need a server capable of sending data updates (like PHP or ASP).

• The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams.

• Code in PHP (demo_sse.php):

Page 183: Advanced html5 for android application development in phonegap

Server-Side Code

<?php

header('Content-Type: text/event-stream');

header('Cache-Control: no-cache');

$time = date('r');

echo "data: The server time is: {$time}\n\n";

flush();

?>

Page 184: Advanced html5 for android application development in phonegap

HTML5 Offline Web Applications

Page 185: Advanced html5 for android application development in phonegap

HTML5 Application Cache

• With application cache it is easy to make an offline version of a web application, by creating a cache manifest file.

Page 186: Advanced html5 for android application development in phonegap

What is Application Cache?

• HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.

• Application cache gives an application three advantages: – Offline browsing - users can use the application when

they're offline

– Speed - cached resources load faster

– Reduced server load - the browser will only download updated/changed resources from the server

Page 187: Advanced html5 for android application development in phonegap

Q/A

Thanks