46
HTML 5

HTML 5

Embed Size (px)

Citation preview

HTML 5

Outlines HTML5 Design Principles HTML5 Feature Detection and Modernizer.js HTML 5 new elements and attributes Media Drawing using:

o Canvaso SVG

Geolocation

Some HTML5 Design Principles

Compatibiliy:o Support existing contento Degrade gracefullyo Do not reinvent the wheelo Pave the cowpathso Evolution not revolution

Utility:o Separation of concernso DOM consistency

Interoperabilityo Well defined behavioro Avoid needless complexityo Handles errors

Feature Detection

if (navigator.geolocation){//supported

} else{//not supported

}

Modernizer.js Modernizr is an open source, MIT-licensed

JavaScript library that detects support for many HTML5 & CSS3 features.

Creates a global object called Modernizr 

if (Modernizr.canvas) { // let's draw some shapes!} else { // no native canvas support available :(}

HTML 5 New Elements <section> is a sematic grouping of content, typically

with a heading. o Web site's home page introduction, news items, contact

information. <nav> is a section of a page that links to other pages

or to parts within the page  <article> represents a component of a page that

consists of a self-contained composition o a forum post, a magazine or newspaper article, a Web log

entry, a user-submitted comment, an interactive widget or gadget 

<aside> Used for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page.

<section id="main"> o <article> <!-- first blog post content goes here -->

</article> o <article> <!-- second blog post content goes here --> o </article> <article> <!-- third blog post content goes

here --> </article> </section>

HTML 5 New Elements (Cont’d)Example

HTML 5 New Elements (Cont’d)Example

<article> o <section id="introduction"> </section> o <section id="content"> </section> o <section id="summary"> </section>

</article>

HTML 5 New Elements (Cont’d)

<time> represents either a time on a 24 hour clock, or a precise date

<mark> represents text marked or highlighted <figure> and <figcaption> represent an image,

chart or code exampleso <figure>o <img src="path/to/image" alt="About image" />o <figcaption>o <p>This is an image of something

interesting. </p>o </figcaption>o </figure>

HTML 5 New Elements (Cont’d)

<hgroup> to group a set of h1–h6 elements when the heading has multiple levels.

<header> contain the section’s heading (an h1–h6 element or an hgroup element) or section’s table of contents, a search form, or any relevant logos.

<footer> represents a footer for a sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.

<header> <hgroup> <h1>My Weblog</h1> <h2>A lot of effort went into making this effortless.</h2> </hgroup> <nav> <ul> <li><a href="../semantics.html">home</a></li> <li><a href="../semantics.html">blog</a></li> <li><a href="../semantics.html">gallery</a></li> <li><a href="../semantics.html">about</a></li> </ul> </nav> </header>

HTML 5 New Elements (Cont’d)Example

<header> <hgroup> <h1>My Weblog</h1> <h2>A lot of effort went into making this effortless.</h2> </hgroup> <nav> <ul> <li><a href="../semantics.html">home</a></li> <li><a href="../semantics.html">blog</a></li> <li><a href="../semantics.html">gallery</a></li> <li><a href="../semantics.html">about</a></li> </ul> </nav> </header>

HTML 5 New Elements (Cont’d)Example

<article> <header> <time datetime="2009-10-22" pubdate>October 22, 2009</time> <h1> <a href="../semantics.html" title="link to this post">Travel day</a> </h1> </header> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec hendrerit felis accumsan turpis pretium tempor. Duis eu turpis nunc, ut euismod nisl. Aliquam erat volutpat. Proin eu eros mollis dui fringilla sodales. Curabitur venenatis tincidunt felis ac congue. Maecenas at odio dui, sit amet congue sapien. </p > </article>

HTML 5 New Elements (Cont’d)Example

<input list="browsers"><datalist id="browsers"> <option value="Others"> <option value="Internet Explorer"> <option value="Firefox"> <option value="Chrome"> <option value="Chrome Mobile"> <option value="Opera"> <option value="Safari"></datalist>

HTML 5 New Elements (Cont’d)

Forms – datalist

<input type="color" >

HTML 5 New Elements (Cont’d)

Forms – color

<input type=“date" >

HTML 5 New Elements (Cont’d)

Forms – date

email contain an e-mail address, the e-mail address will be automatically validated when submitted.

month to select a month and year, a date picker will show up in the input field.

number contain a numeric value.o .max Specifies the maximum value for an input fieldo .min Specifies the minimum value for an input fieldo .pattern Specifies a regular exp to check the input value

againsto .step Specifies the legal number intervals for an input fieldo .stepUp(n) increases the field’s value by n.o .stepDown(n) decreases the field’s value by n.o .valueAsNumber returns the current value as a floating point

number.o <input type="number" name="points" min="0" max="100" 

step="10" value="30">

HTML 5 New Elements (Cont’d)

Forms – Other types

range contain a value within a range, the input field will be displayed as a slider control. The default values from 0 to 100

<input type="range" name="points" min="0" max="10">

Some useful attributes: min, max, step. search search fields (behaves like a regular text field).

Except that when you start typing in it a small cross appears on the right side of the field. This helps clear the content fast.

time to select a time , a time picker can show up in the input field.

url contain a URL address, the url field will be automatically validated when submitted

week to select a week and year, a date picker will show up in the input field.``

HTML 5 New Elements (Cont’d)

Forms – Other types

HTML 5 New Elements New graphic elements:

o <svg> and <canvas>.  New multimedia elements:

o <audio> and <video>.

Media <video src="url/video.ogg" controls>

o Your browser does not support the <code>video</code> element.

</video>

<audio src="/test/audio.ogg">o <p>Your browser does not support the audio

element.</p> </audio>

Media (Cont’d) Multiple Sources <video width="320" height="240" controls

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

</video>

Media APIs video/audio element methods:

o canPlayType() Checks if the browser can play the specified audio/video type

o load() Re-loads the audio/video elemento play() Starts playing the audio/videoo pause() Pauses the currently playing

audio/video

Media APIs video/audio element properties

o autoplay Sets/Gets whether the audio/video should start playing when loadedo buffered Gets a TimeRanges of the buffered parts of the audio/videoo controls Sets/Gets whether the audio/video display controlso currentSrc Gets the URL of the current audio/videoo currentTime Sets/Gets the current playback position (in seconds)o defaultMuted Sets/Gets whether the audio/video should be muted by defaulto defaultPlaybackRate Sets/Gets the default speed of the audio/video playbacko duration Gets the length of the current audio/video (in seconds)o ended Gets whether the playback of the audio/video has ended or noto error Gets a MediaError object, the error state of the audio/videoo loop Sets/Gets whether the audio/video automatically start over againo muted Sets/Gets whether the audio/video is muted or noto networkState Gets the current network state of the audio/videoo paused Gets whether the audio/video is paused or noto playbackRate Sets/Gets the speed of the audio/video playbacko played Gets a TimeRanges object of the played parts of the audio/videoo preload Sets/Gets whether audio/video is loaded on page loado readyState Gets the current ready state of the audio/videoo seekable Gets a TimeRanges object, the seekable parts of the audio/videoo seeking Gets whether the user is currently seeking in the audio/videoo src Sets/Gets the current source of the audio/video elemento startDate Gets a Date object representing the current time offseto volume Sets/Gets the volume of the audio/video

Media APIs video/audio element events

o abort Fires when the loading is abortedo canplay Fires when the browser can start playing o canplaythrough Fires when the browser can play without stopping for bufferingo durationchange Fires when the duration is changed (after it is loaded)o ended Fires when the audio/video has endedo error Fires when an error occurred during loadingo loadeddata Fires when the browser has loaded the current frame o loadedmetadata Fires when the browser has loaded meta data o loadstart Fires when the browser starts looking for the audio/videoo pause Fires when been pausedo play Fires when started or is not pausedo playing Fires when playing after being paused or stopped for

bufferingo progress Fires when downloading the audio/videoo ratechange Fires when the playing speed is changedo seeked Fires when the user finish moving/skipping to a new positiono seeking Fires when the user starts moving/skipping to a new positiono stalled Fires when browser is trying to get media data, but data is N/Ao suspend Fires when the browser is intentionally not getting media datao timeupdate Fires when the current playback position has changedo volumechange Fires when the volume has been changedo waiting Fires when the video stops to buffer the next frame

Media Events Life Cycle

loadstart o durationchange • loadedmetadata • loadeddata • progress • canplay • canplaythrough

Drawing using Canvas Canvas:“a strong, coarse unbleached cloth used to make items such as sails and tents and

as a surface for oil painting.” Used to:

o draw graphics, o make photo compositions, real-time video processing or rendering. o create animations

The default size of the canvas is 300 px × 150 px (width × height).o <canvas id="c1"></canvas>o <script>o var canvas = document.getElementById("c1");o var ctx = canvas.getContext("2d");o ctx.fillStyle = "green";o ctx.fillRect(10, 10, 100, 100);o </script>

Drawing using Canvas (Cont’d)

Coloro ctx.fillStyle = "green";o ctx.strokeStyle = "green”;o fillStyle and strokeStyle sets the colors used for

rendering filled/framed shapeso Can use gradient object or a pattern

To clear canvas:o ctx.clearRect(x,y,width,height);

How to creates a gradients or a pattern?

Drawing using Canvas (Cont’d)

Line:o to move to the starting point, Set the endpoint, o Draw a line between them 

• ctx.moveTo(60,0);• ctx.lineTo(60,153);• ctx.stroke(); 

You can set multiple line to be drawn at once instead using path o ctx.beginPath();o ctx.strokeStyle="red";o ctx.moveTo(60,173);o ctx.lineTo(60,375);o ctx.moveTo(60,390);o ctx.lineTo(270,390);o ctx.moveTo(270,375);o ctx.lineTo(270,173);o ctx.stroke();o ctx.closePath();

Drawing using Canvas (Cont’d)

Rectangleo ctx.fillRect(10, 10, 100, 100); // x, y, width, heighto ctx.strokeRect(10,10,100,100) // only edges , no fillo ctx.clearRect(10,10,100,100) // clear part of the

canvas rep. by the rect Arc/Circles

o ctx.arc(x,y,radius,startAngle,endAngle,anticlockwise) Text

o ctx.font=”bold 12px sans-serif”; // CSS font ruleo ctx.textAlign=”center”; //start, end, left, right,

centero ctx.fillText(“str”,x,y); // print str as a text

starting from x and y

Drawing using SVG Scalable Vector Graphics

o Describes 2D graphics in XMLo Ideal for handling different screen sizeso Resolution independent

<svg id=“svgelem” height=“200” xmlns=“”>o <circle id=“redcircle” cx=“50” cy=“50” r=“50”

fill=“red” /> </svg>

http://www.w3.org/TR/SVG/

CANVAS or SVG?

The QUESTION is:

Geolocation navigator.geolocation object Getting the current position

o getCurrentPosition( sucesscallback, errorcallback, geo_options)o navigator.geolocation.getCurrentPosition(function(position

) { alert(position.coords.latitude+”-”+position.coords.longitude); }); 

Watching the current positiono watchPosition(successcallback, errorcallback, geo_options)

PositionOptions Objecto var geo_options = {o enableHighAccuracy: true, o maximumAge : 30000, o timeout : 27000o };

Drag and Drop Steps:

o Define a draggable target using draggable attributeo Define data to be dragged (ondragstart)

• Text, Links, HTML and XML• Files, Images• Document Nodes

o Define custom drag feedback imageo Define drag effect

• copy, move, linko Define Drop areao Do something when drop occurs

http://html5demos.com/drag

Drag and Drop (Cont’d)

Drag Eventso dragstarto dragentero dragovero dragleaveo drago dropo dragend

Drag and Drop (Cont’d)

Default drag behaviouro text selectiono Imageso links

To make other elements draggableo Set draggable=trueo Add a listener for the dragstart eventso Set drag data within the listener defined above

<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'This text may be dragged')”>o This text <strong>may</strong> be dragged.

</div>

Drag and Drop (Cont’d)

dragstart event used to:o Specify drag data

• Drag event has property dataTransfer contains format and value

o Feedback image o Drag effect

Drag and Drop (Cont’d)

dragenter/dragover event for drop target elementso Can be used to check whether drop is allowed to be

dropped by checking dataTransfer data type/format

Drag and Drop (Cont’d)

dragstart event used to:o Specify drag data

• Drag event has property dataTransfer contains format and value

o Feedback image o Drag effect

Drag and Drop (Cont’d)

Droppingo Handle Drop event

• Prevent browser default behavior (redirection)

Drag and Drop (Cont’d)

Web Storage First there were cookies

o Included in each requesto Max 4KBo Can be turned off

HTML5 Web Storage:o Local Storageo Session Storage

Session Storage Persist data for the duration of the page session.

o As long as browser is open, survive reloadso New tab/ new window new session

Add/edit/delete the sessionStorage object Saved in a key/value pair

o sessionStorage.setItem(‘name’,’John’); Or sessionStorage.name=‘John’

o var item=sessionStorage.getItem(‘name’);o sessionStorage.removeItem(‘name’);o sessionStorage.clear();

Local Storage Persist data until history cleared Add/edit/delete the localStorage object Saved in a key/value pair

o localStorage.setItem(‘name’,’John’); Or localStorage.name=‘John’

o var item=localStorage.getItem(‘name’);o localStorage.removeItem(‘name’);o localStorage.clear();

To store objects Serialize them into JSON string then save them

o JSON.stringify(jsobject) json string When retrieving deserialize the JSON string into

an objecto JSON.parse(jsonstr) javascript object

Reading Assignment What is HTML 5 Microdata? What is Web Worker API? What is Application Cache? What is IndexedDB?