lecturer: roi yehoshua [email protected] html5 open day 05/09/2012

115
Lecturer: Roi Yehoshua [email protected] HTML5 Open Day 05/09/2012

Upload: colin-newsum

Post on 15-Dec-2015

240 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Lecturer: Roi [email protected]

HTML5 Open Day

05/09/2012

Page 2: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Agenda

• HTML 5.0 Introduction• Overview of HTML5 new features• Overview of CSS3 capabilities and new features

©Roi Yehoshua, 20122

Page 3: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Introduction

• HTML5 is the next generation of HTML and it will be the new standard for HTML, XHTML, and the HTML DOM.

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

• HTML5 introduces a collection of new features - rich typography, native audio & video, powerful drawing and image manipulation API – allows you to create web pages with unparalleled user experience.

©Roi Yehoshua, 20123

Page 4: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML Timeline

©Roi Yehoshua, 20124

Page 5: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Goals

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

• Reduce the need for external plugins (like Flash or Silverlight)• Better error handling• More markup to replace scripting• HTML5 should be device independent• The development process should be visible to the

©Roi Yehoshua, 20125

Page 6: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 New Features• New structural elements• Canvas• <video> and <audio> tags• Geolocation• Form enhancements• Web Storage• Web SQL• Web Socket• Web Workers

• Offline web applications• Web GL• Drag and drop• FileSystem API• History API• Messaging API• Desktop Notifications• And more…

©Roi Yehoshua, 20126

Page 7: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Desktop Browser Support

©Roi Yehoshua, 2012 ©Roi Yehoshua, 20127

Page 8: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The Mobile Web Challenge• The mobile web is massive

• 10+ billion web-enabled mobile devices by 2013• Each mobile platform has its own programming

language• iPhone apps are written in Objective C.• Android apps are written in Java.• Symbian apps are written in C++.• Blackberry apps are written in Java (but not the• same Java as Android).• WinPhone apps are written in .NET

©Roi Yehoshua, 20128

Page 9: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Mobile Web• Web technology is the one thing all devices have

in common• Using HTML, CSS and JavaScript, we can write

applications that will run on any device.• These apps can run online or offline using HTML5

offline capabilities• Web apps can integrate special device

capabilities to create Hybrid Applications ©Roi Yehoshua, 20129

Page 10: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

One codebase, all platforms

©Roi Yehoshua, 201210

Page 11: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

jQuery Mobile• A unified, HTML5-based user interface system for all

popular mobile device platforms• Built on the rock-solid jQuery and jQuery UI libraries• Implements native looking UI components• Latest stable version 1.1.1 (July 2012)

©Roi Yehoshua, 201211

Page 12: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Real-World jQM

©Roi Yehoshua, 201212

http://www.jqmgallery.com/

Page 13: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

PhoneGap• PhoneGap is an open-source mobile development

framework "connecting" solution from mobile web to native.

• It enables to build applications for mobile devices using JavaScript, HTML5 and CSS3, instead of often less-known languages such as Objective-C.

©Roi Yehoshua, 201213

Page 14: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Hybrid Apps

©Roi Yehoshua, 201214

Page 15: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

PhoneGap Selected Apps

©Roi Yehoshua, 201215

Page 16: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web vs. Native

©Roi Yehoshua, 201216

WebNative

CodingWrite once, test everywhere

Write everywhere, test everywhere

Device CapabilitiesUse limited device capabilities

Use full device capabilities

Look & FeelBuild your own UI components

Use device UI Components

Typical Use CasesProvide informationabout service/businessM-Commerce (Mobile online shop)Simple games

Photo taking app3D or complex games

Page 17: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Editors• HTML5 Open Source Editors

• Komodo Edit http://www.activestate.com/komodo-edit• Maquetta, IBM’s open source WYSIWYG HTML5 Editor

http://maqetta.org/• Many other HTML5 editors are available on the web

• The Helios release of the Eclipse IDE for Java EE Developers provides support for HTML5 development.

• Visual studio 2010 SP1 has a Web Standards Update that adds HTML5 and CSS3 support• http://visualstudiogallery.msdn.microsoft.com/a15c3ce9-

f58f-42b7-8668-53f6cdc2cd83 ©Roi Yehoshua, 201217

Page 18: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The HTML5 Skeleton• DOCTYPE is always the first tag but no URL required• Required by browsers to trigger a standards mode

• Character encoding is optional but should be present

• This is all you need to set encoding• content and http-equiv are allowed but not required

• No need to specify type attribute in <script> and <link> tags

©Roi Yehoshua, 201218

!>DOCTYPE html< !>DOCTYPE html<

<meta charset="utf-8" /><meta charset="utf-8" />

Page 19: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Basic HTML5 Page

©Roi Yehoshua, 201219

<!DOCTYPE html><html><head> <title>My Amazing Page</title> <meta charset="utf-8" /> <link href="style.css" rel="stylesheet" /> <script> alert("Hello there"); </script></head><body> This is my first HTML5 page</body></html>

<!DOCTYPE html><html><head> <title>My Amazing Page</title> <meta charset="utf-8" /> <link href="style.css" rel="stylesheet" /> <script> alert("Hello there"); </script></head><body> This is my first HTML5 page</body></html>

Page 20: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 new structural tags• HTML5 has a series of new structural elements

• To create a more semantically structured page• The main building blocks of HTML5 are:

• <header>• <nav>• <section>• <article>• <footer>

©Roi Yehoshua, 201220

Page 21: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas• Canvas is an API for 2D drawing• Canvas is resolution-independent bitmap, which could be

used for rendering graphs, game graphics or other visual graphics on the fly

• No plug in required and supported heavily now• Could become a competitor to Flash and Silverlight once

the feature set and IDE designers become more adept• IE versions earlier than 9 can use third-party canvas library

plugin to make it work

©Roi Yehoshua, 201221

Page 22: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Using Canvas• The <canvas> element is a container

• Write to it by first getting a reference to the object

• Every canvas has a drawing context

• Then use this reference to draw

©Roi Yehoshua, 201222

< canvasid "myCanvas"=width "300"=height220"=>/“

<canvas id="myCanvas" width="300" height="220>/“

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

var context = canvas.getContext(“2d");var context = canvas.getContext(“2d");

context.fillRect(25, 25, 150, 100);context.fillRect(25, 25, 150, 100);

Page 23: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Drawing Rectangle example

©Roi Yehoshua, 201223

<head> <script> function drawRect() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");  context.fillStyle = "blue"; context.fillRect(25, 25, 150, 100); } </script></head><body onload="drawRect();"> <canvas id="myCanvas" width="300" height="220"> Update your browser to enjoy canvas! </canvas></body></html>

<head> <script> function drawRect() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");  context.fillStyle = "blue"; context.fillRect(25, 25, 150, 100); } </script></head><body onload="drawRect();"> <canvas id="myCanvas" width="300" height="220"> Update your browser to enjoy canvas! </canvas></body></html>

Page 24: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Drawing Paths Example

©Roi Yehoshua, 201224

function drawTriangle() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");  context.beginPath(); context.moveTo(50, 50); context.lineTo(50, 150); context.lineTo(100, 100); context.fillStyle = “red”; context.fill();}

function drawTriangle() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d");  context.beginPath(); context.moveTo(50, 50); context.lineTo(50, 150); context.lineTo(100, 100); context.fillStyle = “red”; context.fill();}

Page 25: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Drawing Images Example

©Roi Yehoshua, 201225

function drawImage() { var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d');  var img = new Image(); img.src = "images/koala.jpg";  img.onload = function () { context.drawImage(img, 0, 0, 400, 360); };

function drawImage() { var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d');  var img = new Image(); img.src = "images/koala.jpg";  img.onload = function () { context.drawImage(img, 0, 0, 400, 360); };

Page 26: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas Image Filtering• It’s possible to paint a png or jpeg image on a

canvas using drawImage• Canvas also lets JS code take the pixels from

the image into an array. Using this array, we can transform the pixels and write the result to a new canvas

• The operation is called filtering

©Roi Yehoshua, 201226

Page 27: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas Image Filtering

©Roi Yehoshua, 201227

function filterImage{ () var)img = document.getElementById "sourceImage"(;

varwidth = img.width ; varheight = img.height ;

var)canvas = document.createElement "canvas"(;

canvas.width = width; canvas.height = height;

var)context = canvas.getContext "2d"(;

context.drawImage(img, 0, 0);

//Grab the pixel data from the canvas varimageData = context.getImageData(0, 0, width, height) ;

vardata = imageData.data ;

grayScale(imageData);

context.putImageData(imageData, 0, 0); img.src = canvas.toDataURL;()

}

function filterImage{ () var img = document.getElementById("sourceImage");

var width = img.width; var height = img.height;

var canvas = document.createElement("canvas");

canvas.width = width; canvas.height = height;

var context = canvas.getContext("2d");

context.drawImage(img, 0, 0);

//Grab the pixel data from the canvas var imageData = context.getImageData(0, 0, width, height);

var data = imageData.data;

grayScale(imageData);

context.putImageData(imageData, 0, 0); img.src = canvas.toDataURL;()

}

Page 28: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas Image Filtering

©Roi Yehoshua, 201228

function grayScale(imageData){ vardata = imageData.data ;

//Loop through the pixels, turning them grayscale

for) var(i = 0; i < data.length; i += 4 { varr = data[i] ;

varg = data[i + 1] ; varb = data[i + 2] ;

varv = (3 * r + 4 * g + b) / 8 ;

data[i] = v; data[i + 1] = v; data[i + 2] = v;

}

imageData.data = data;}

function grayScale(imageData){ var data = imageData.data;

//Loop through the pixels, turning them grayscale

for (var i = 0; i < data.length; i += 4){ var r = data[i];

var g = data[i + 1]; var b = data[i + 2];

var v = (3 * r + 4 * g + b) / 8;

data[i] = v; data[i + 1] = v; data[i + 2] = v;

}

imageData.data = data;}

Page 29: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas Image Filtering

©Roi Yehoshua, 201229

Page 30: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Games created with Canvas• A first person shooter

• http://www.benjoffe.com/code/demos/canvascape/textures

• Asteroids• http://www.kevs3d.co.uk/dev/

asteroids/• Other games

• http://savedelete.com/best-html5-canvas-games.html

©Roi Yehoshua, 201230

Page 31: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

SVG• SVG is an alternative W3C spec for creating

graphics• SVG stands for Scalable Vector Graphics and it is

a language for describing 2D-graphics and graphical applications in XML.

• SVG is mostly useful for vector type diagrams like Pie charts, two-dimensional graphs etc.

©Roi Yehoshua, 201231

Page 32: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Embedding SVG in HTML5• HTML5 allows embedding SVG directly

using the <svg> tag

©Roi Yehoshua, 201232

!>DOCTYPE html<>head<

>title<SVG/>title< >meta charsetutf-8"=" </

/>head<>body<

>h2<HTML5 SVG Circle/>h2< >svg id"svgelem"=

xmlnshttp://www.w3.org/2000/svg"=<" >circle id"redcircle"= cx"50"= cy"50"= r"50"=

fillred"=" </ />svg<

/>body</>html<

!>DOCTYPE html<>head<

>title>SVG</title< >meta charset="utf-8" </

/>head<>body<

>h2>HTML5 SVG Circle</h2< >svg id="svgelem"

xmlns="http://www.w3.org/2000/svg<" >circle id="redcircle" cx="50" cy="50" r="50"

fill="red" </ />svg<

/>body</>html<

Page 33: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Canvas vs. SVG• Vectors vs. Pixels

• SVG is vector based• Canvas offers pixel operations

• Document vs. Script• SVG images are defined in XML• Canvas is script-based and requires JavaScript

• SVG is best suited to scalable and interactive graphics• Canvas is the best option for fast games or animations• SVG is a plug-in for IE8 or less

©Roi Yehoshua, 201233

Page 34: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Multimedia• Multimedia support has always been a delivery

issue• Commonly the <object> tag provided the support

• With a classid attribute to denote the plugin required• The non-standard <embed> may also be nested for

legacy browser support• Execution is then passed from the browser to a

plugin• User must have a correct version of plugin

©Roi Yehoshua, 201234

Page 35: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Video• The <video> element has a src attribute

• By default shows first frame of video but does not start

• Add an autoplay attribute to initialize• Add controls attribute for user control

• In the same way as <object> add legacy support

©Roi Yehoshua, 201235

<video src="myvideo.mp4" autoplay controls> <p>Your browser fights the future!</p></video>

<video src="myvideo.mp4" autoplay controls> <p>Your browser fights the future!</p></video>

Page 36: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The Codec Issue• The HTML5 spec does not mandate a specific video

format• YouTube has already moved to a HTML5 video

support based on Apple’s H.264 codec• Both Firefox and Opera have refused to use H.264

because it’s heavily patented and expensive• Google have provided an open source alternative

called WebM• Broad support• Not from Apple

©Roi Yehoshua, 201236

Page 37: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The Source element

• Media must be supported in multiple formats• The <source> element gives multiple chances

• Use instead of src attribute on video tag

©Roi Yehoshua, 201237

>video id"myVideo"= width"600"= height"400"= controls autoplay loop<

>source srcvideo/big_buck_bunny.mp4"=" </ >source srcvideo/big_buck_bunny.ogv"=" </

>source srcvideo/big_buck_bunny.webm"=" <//>video<

>video id="myVideo" width="600" height="400" controls autoplay loop<

>source src="video/big_buck_bunny.mp4" </ >source src="video/big_buck_bunny.ogv" </

>source src="video/big_buck_bunny.webm" <//>video<

Page 38: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Video API• <video> element can be controlled via JavaScript

• Used to give a consistent cross browser feel• Or dynamic functionality

©Roi Yehoshua, 201238

function toggleVideo{ () var)video = document.getElementById "myVideo"(;

if(video.paused)

video.play;() else

video.pause;()}

function toggleVideo{ () var video = document.getElementById("myVideo");

if (video.paused)

video.play;() else

video.pause;()}

Page 39: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Video API• currentTime attribute

• When read, this attribute returns the current playback position in seconds

• Setting this attribute will, if possible, move the playback position to the specified time index.

• Media events• Loadstart• Play• Seeking• timeupdate

©Roi Yehoshua, 201239

Page 40: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Video API Demo• http://www.w3.org/2010/05/video/mediaevents.html

©Roi Yehoshua, 201240

Page 41: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Audio• Almost identical to the video element

• source elements need to be used

©Roi Yehoshua, 201241

>audio controls autoplay< >source srcaudio/bach_air.mp3"=" </ >source srcaudio/bach_air.ogg"=" </

Your browser doesn't support HTML5 Audio/>audio<

>audio controls autoplay< >source src="audio/bach_air.mp3" </ >source src="audio/bach_air.ogg" </

Your browser doesn't support HTML5 Audio/>audio<

Page 42: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Combining Canvas with Video Effects

• http://www.craftymind.com/factory/html5video/CanvasVideo.html

©Roi Yehoshua, 201242

Page 43: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Local Storage

• Local storage will mean the death of cookies• Problems with cookies:

• Cookies are limited to 4KB of data and 20 per domain• Cookies are included in every HTTP request

• Wasteful plus potential bandwidth issues• Potential security issues

• What modern web apps need is:• More storage space• Client based

©Roi Yehoshua, 201243

Page 44: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Local Storage• Local storage can store up to 5MB (per site)• The storage API offers two modes:

• sessionStorage – available to the window until the window is closed

• localStorage – spans all windows that are open on that domain. The data will last until you want to get rid of it.

• Web storage has very good browser support

©Roi Yehoshua, 201244

Page 45: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Working with Local Storage• Web storage is based on named key/value pairs

• Retrieve data based upon the key• Key is a string value

• Value can be any JavaScript type but is held as string• Must be parsed into correct type• Using parseInt() or similar

• Local storage can be treated like an associative array• Method based or array based approach• Can be used for more complex JSON structures

©Roi Yehoshua, 201245

Page 46: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Working with Local Storage• Use setItem() method to save the key-value pair

• Read data with getItem() parsing when necessary

• Can also use direct access on the storage object (using JavaScript expando properties)

©Roi Yehoshua, 201246

localStorage.setItem("thing", 5); //or

)sessionStorage.setItem"key" ,"value"(;

localStorage.setItem("thing", 5); //or

sessionStorage.setItem("key", "value");

var x =

parseInt(localStorage.getItem("thing"));

var x =

parseInt(localStorage.getItem("thing"));

localStorage.thing = 5;

varx = parseInt(localStorage.thing) ;

localStorage.thing = 5;

var x = parseInt(localStorage.thing);

Page 47: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Exploring Web Storage State• Webkit browsers have the best support for looking at what is

being stored in each storage type in their web inspector

©Roi Yehoshua, 201247

Page 48: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Dealing with Complex Objects

• AJAX applications often hold JSON data structures

• Using a JSON serialization we can add it to local storage

©Roi Yehoshua, 201248

Page 49: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

JSON and JavaScript

©Roi Yehoshua, 201249

• JSON is a subset of the object literal notation of JavaScript– Can be used in the JS language with no problemsvar myJSONObject = { "searchResults": [ { "productName": "Aniseed Syrup", "unitPrice": 10 }, { "productName": "Alice Mutton", "unitPrice": 39 } ]};

var myJSONObject = { "searchResults": [ { "productName": "Aniseed Syrup", "unitPrice": 10 }, { "productName": "Alice Mutton", "unitPrice": 39 } ]};

alert(myJSONObject.searchResults[0].productName); //

alerts "Aniseed Syrup"

alert(myJSONObject.searchResults[0].productName); //

alerts "Aniseed Syrup"

• Can use dot or subscript operators to access members

Page 50: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

JSON Serialization

©Roi Yehoshua, 201250

• There are two JSON methods in JavaScript:• JSON.stringify(obj) — converts an JavaScript

object to a JSON string• JSON.parse(str) — converts a JSON string back

to a JavaScript object• Supported from ECMAScript5 (IE9 and

above) or can use json2 library (http://www.json.org/json2.js)

Page 51: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

JSON Serialization

©Roi Yehoshua, 201251

localStorage.products = JSON.stringify(products);varp = JSON.parse(localStorage.products) ;localStorage.products = JSON.stringify(products);var p = JSON.parse(localStorage.products);

Page 52: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Get JSON from Server

©Roi Yehoshua, 201252

$.ajax({

type: 'POST',

url: url,

dataType: 'json',

data: data,

success: function (data)

{

}

});

$.ajax({

type: 'POST',

url: url,

dataType: 'json',

data: data,

success: function (data)

{

}

});

$.getJSON('ajax/test.json',

function (data) {

});

$.getJSON('ajax/test.json',

function (data) {

});

Page 53: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web SQL

• Web SQL gives us the ability to create a real database client side• Using SQLite (http://sqlite.org)

• Limited to 5Mb in size• Currently supported only by Chrome, Safari and Opera• Web SQL may be dead end in development

• Mozilla and Microsoft are hesitant to implement support• An asynchronous API that uses callback functions

©Roi Yehoshua, 201253

Page 54: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Create and Open Database• If you try to open a database that doesn’t exist, the API

will create it on the fly for you. You also don’t have to worry about closing databases.

• Parameters:• Database name• Version number• Text description• Estimated size of database

©Roi Yehoshua, 201254

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);

Page 55: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Execute SQL• executeSql() is used for both read and write

statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written.

• All SQL statements are performed under a transaction

©Roi Yehoshua, 201255

db.transaction(function (tx){ )tx.executeSql CREATE TABLE IF NOT EXISTS foo (id'

'(unique, text(; )tx.executeSql INSERT INTO foo (id, text) VALUES'

'(? ,?)([id, userValue] ,;;(}

db.transaction(function (tx){ tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id

unique, text)'); tx.executeSql('INSERT INTO foo (id, text) VALUES

(?, ?)', [id, userValue]);;(}

Page 56: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Execute SQL• To select values from the table, you can use a callback

to capture the results:

©Roi Yehoshua, 201256

tx.executeSql('SELECT * FROM foo', [], function (tx, results){

varlen = results.rows.length, i ; for(++i = 0; i < len; i) {

alert(results.rows.item(i).text);} ;(}

tx.executeSql('SELECT * FROM foo', [], function (tx, results){

var len = results.rows.length, i; for (i = 0; i < len; i++){

alert(results.rows.item(i).text);} ;(}

Page 57: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Forms

• HTML5 defines many new input types and attributes to create more meaningful fields and use less unnecessary classes and ids

• HTML5 provides validation tags that need no scripting• Less files to deliver• Less chance of client validation being bypassed

• The most complete part of the HTML5 spec

©Roi Yehoshua, 201257

Page 58: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

New Input Elements• HTML5 adds 13 new type options• Mostly extend the <input> tags with new type values• If a browser doesn’t understand, the extension is

rendered as <input type=“text”>• No requirement in the spec for how browsers present

• Different browsers show different UI and error messages

©Roi Yehoshua, 201258

Page 59: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

HTML5 Forms Browser Support

©Roi Yehoshua, 201259

Page 60: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

New Input Elements

• HTML5 adds 13 new type options• Mostly extend the <input> tags with new type values• If a browser doesn’t understand, the extension is

rendered as <input type=“text”>• No requirement in the spec for how browsers present

• Different browsers show different UI and error messages

©Roi Yehoshua, 201260

Page 61: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Email Input Type• Add type value of email

• <input type=“email”>• What happens in the client is not

consistent• Safari and Opera provides submit

validation• Firefox provides client validation on blue• Safari Mobile changes the input keyboard• IE does nothing

• It is an easy win for a small change ©Roi Yehoshua, 201261

Page 62: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Number Input Type• Numbers often need to be constrained by range• New number type provides this functionality

• Four attributes:• min – lowest value• max – highest value• step – what value the control enumerates by• value – default value

©Roi Yehoshua, 201262

< inputtype "number"=min "1"=max "20"=step "2"=value5"= ">/

<input type="number" min="1" max="20" step="2" value="5 ">/

Page 63: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Number Input Type• Browser support issues

• Chrome and Opera display these as ‘spinboxes’ (like numeric-up down control in Windows Forms)

• No other desktop browsers support this input yet

• Mobile browsers display a different virtual keyboard to assist the user

©Roi Yehoshua, 201263

Page 64: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Range Input Type• Creates a slider bar

• Currently supported only by Chrome and Opera• Not even Safari Mobile

• Has the same attributes as the number type

©Roi Yehoshua, 201264

<input name="age" type="range" min="0" max="120" value="37" /><input name="age" type="range" min="0" max="120" value="37" />

Page 65: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Date Input Type

©Roi Yehoshua, 201265

<input type"date"= id"dateofbirth"= namedateofbirth"=" >/

<input type="date" id="dateofbirth" name="dateofbirth" >/

In Chrome

In Opera

Page 66: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Form Validation

• HTML5 defines 8 types of input validations• These are JavaScript free client validation• Browser support is currently limited

• IE offers no UI implementation in any version• Firefox and Opera offers the most complete

implementation• Chrome is pretty good and Safari is getting better

• Some controls have silent errors, not enough UI feedback

©Roi Yehoshua, 201266

Page 67: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Required Fields

• You can force a field to be mandatory on the client• This can be achieved by adding the required

attribute to an input, select or textarea element• An error message will appear on submit action

©Roi Yehoshua, 201267

<input type="text" id="name" name="name" required/><input type="text" id="name" name="name" required/>

Page 68: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Type Validations• Using the new HTML5 input fields, you can

explicitly create inputs for things like numbers, email addresses and URLs.

• Browsers can validate the input fields in these more specific fields against a built-in pattern that defines what valid entries in those types

©Roi Yehoshua, 201268

<input type="email" /><input type="email" />

Page 69: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Pattern Validations

• You can use the pattern attribute to specify your own custom regular expression.

©Roi Yehoshua, 201269

<input type="tel" id="phone" name="phone"

pattern="[0-9]{2,3}-[0-9]{7}"/>

<input type="tel" id="phone" name="phone"

pattern="[0-9]{2,3}-[0-9]{7}"/>

Page 70: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Custom Validation Messages

• You can set a custom validation message using the method element.setCustomValidity(message)

©Roi Yehoshua, 201270

function check(input){ if(()input.checkValidity!) {

)input.setCustomValidity"' Dude" + input.value + "!!is not a valid email. Enter something nice '"(;

} else{

input.setCustomValidity)"";(} }

function check(input){ if (!input.checkValidity()){

input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");

} else{

input.setCustomValidity)"";(} }

Page 71: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Custom Validations• You can use setCustomValidity() to add your own

custom validations, for example when the confirm password doesn’t match the original password.

©Roi Yehoshua, 201271

function checkPasswords() { var pass = document.getElementById("password"); var confirmPass = document.getElementById("confirmPassword");  if (pass.value != confirmPass.value) confirmPass.setCustomValidity("Passwords do not match"); else confirmPass.setCustomValidity("");}

function checkPasswords() { var pass = document.getElementById("password"); var confirmPass = document.getElementById("confirmPassword");  if (pass.value != confirmPass.value) confirmPass.setCustomValidity("Passwords do not match"); else confirmPass.setCustomValidity("");}

Page 72: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Styling with CSS3

©Roi Yehoshua, 201272

<head>< styletypetext/css"=>"

input[type=text]:focus:valid, input[type=email]:focus:valid,

input[type=number]:focus:in-range { :outline2px green solid} ;

input[type=text]:focus:invalid, input[type=email]:focus:invalid,

input[type=number]:focus:out-of-range { :outline2px red solid } ;

/< style >/<head>

>body< > formid<"frm1"= > labelfor/>:email">E-mail"=label< > inputtype "email"=id "email"=name</ "email"= > br </ />form</>body<

<head>< style type="text/css>"

input[type=text]:focus:valid, input[type=email]:focus:valid,

input[type=number]:focus:in-range { outline: 2px green solid} ;

input[type=text]:focus:invalid, input[type=email]:focus:invalid,

input[type=number]:focus:out-of-range { outline: 2px red solid } ;

/< style >/<head>

<body> <form id="frm1"> <label for="email">E-mail:</label> <input type="email" id="email" name="email" /> <br /> </form></body>

Page 73: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Placeholder attribute• The placeholder attribute offers default text

• Gives the user example or instruction for the field• Sometimes called a watermark• Can only be used for text fields

©Roi Yehoshua, 201273

<input type="text" id="name" name="name" placeholder="First and last name" <input type="tel" id="phone" name="phone" placeholder="xx(x)-xxxxxxx"/>

<input type="text" id="name" name="name" placeholder="First and last name" <input type="tel" id="phone" name="phone" placeholder="xx(x)-xxxxxxx"/>

Page 74: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Geolocation• Geolocation API lets you share your

location with trusted web sites• The latitude and longitude are available

to JavaScript on the page• Enables to provide location-aware

things like finding local businesses or showing your location on a map

©Roi Yehoshua, 201274

Page 75: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Get Location• navigator.geolocation is the entry point for all location

related calls• To get hold of the user’s current position use the

getCurrentPosition() method

• Location querying is asynchronous, so a callback is supplied• Mandatory success callback, optional error method

©Roi Yehoshua, 201275

navigator.geolocation.getCurrentPosition(showLocation, handleLocationError);navigator.geolocation.getCurrentPosition(showLocation, handleLocationError);

Page 76: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Get Location• When user agrees, a position object is passed to the

success method

• Position object has two properties• coords – list of properties about location (next slide)• timesatmp – date and time when location was calculated

©Roi Yehoshua, 201276

function showLocation(position){ varlat = position.coords.latitude ;

varlong = position.coords.longitude ; varwhen = position.timestamp ;

}

function showLocation(position){ var lat = position.coords.latitude;

var long = position.coords.longitude; var when = position.timestamp ;

}

Page 77: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Coords object• Only latitude, longitude and accuracy are guaranteed • Depends on device whether the other are supported

©Roi Yehoshua, 201277

PropertyTypeDescription

latitudedoubleDecimal degrees

longitudedoubleDecimal degrees

altitudedouble or nullMeters above the referenced ellipsoid

accuracydouble Meters

altitudeAccuracydouble or nullMeters

headingdouble or nullDegrees clockwise from true north

speeddouble or nullMeters/second

Page 78: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Location Tracking• Receive notifications about location changes• Can be used for navigation apps, sport apps, and more• Use navigation.getolocation.watchPosition() to start

watching a user’s position

• The method returns a watch id. Keep it. When tracking is no longer needed, use clearWatch() with the watch id to stop.

• The callback of watchPosition will get called every time location has changed

©Roi Yehoshua, 201278

navigator.geolocation.watchPosition(success, error);navigator.geolocation.watchPosition(success, error);

Page 79: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Google Maps API• A JavaScript API to display embedded

maps in web sites• Works on both desktop and mobile

devices• Free to use• Full documentation:

http://code.google.com/apis/maps/documentation/javascript/

©Roi Yehoshua, 201279

Page 80: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Google Maps API• Add the following JavaScript to your page:

• Assign a special empty div that will contain the map. Recommended size of the div is entire page.

• Display the map by creating a google.maps.Map object• To initialize a Map, first create a Map options object to

contain map initialization variables and pass it to the Map object

©Roi Yehoshua, 201280

<script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script><script src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>

<div id="map" style="width:100%; height:100%"></div>

<div id="map" style="width:100%; height:100%"></div>

Page 81: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Google Maps API

©Roi Yehoshua, 201281

var ns = google.maps;var map;

function init() { var opts = { center: new ns.LatLng(0, 0), zoom: 1, mapTypeId: ns.MapTypeId.HYBRID // or ROADMAP or SATELLITE };  map = new ns.Map(document.getElementById("map"), opts); }

var ns = google.maps;var map;

function init() { var opts = { center: new ns.LatLng(0, 0), zoom: 1, mapTypeId: ns.MapTypeId.HYBRID // or ROADMAP or SATELLITE };  map = new ns.Map(document.getElementById("map"), opts); }

Page 82: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Update Location on Map

©Roi Yehoshua, 201282

function updateLocation { () ,navigator.geolocation.getCurrentPosition(success

(error ;} functionsuccess(position) {

var = latlng new ,ns.LatLng(position.coords.latitude (position.coords.longitude ;

map.setCenter(latlng); map.setZoom(17);

}

function updateLocation { () navigator.geolocation.getCurrentPosition(success,

error) ;} function success(position) {

var latlng = new ns.LatLng(position.coords.latitude, position.coords.longitude) ;

map.setCenter(latlng); map.setZoom(17);

}

Page 83: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Markers

• Markers identify points on the map.• Place markers on the map using google.maps.Marker• Markers can receive "click" events, and are often used

within event listeners to bring up info windows.

©Roi Yehoshua, 201283

function drawMarker(latlng) { = markernewns.Marker {)

position: latlng, map: map,

:titleYou are here''! ;(} }

function drawMarker(latlng) { marker = new ns.Marker{)

position: latlng, map: map,

title: 'You are here'! ;(} }

Page 84: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Markers

©Roi Yehoshua, 201284

Page 85: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Offline Applications• HTML5 introduces new methods for enabling a web

site or web application to function without a network connection.

• When you’re working on a mobile connection and your signal drops having some level of access is better than nothing.

• Can run a completely offline app as a standalone

©Roi Yehoshua, 201285

Page 86: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Manifest File• The application cache is controlled by a plain text file

with a .manifest extension• Contains a list of resources to be stored for use when

there is no network connectivity. • If the user goes offline but has visited the site while

online, the cached resources will be loaded so the user can still view the site in a limited form.

©Roi Yehoshua, 201286

Page 87: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Manifest File

©Roi Yehoshua, 201287

Page 88: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Manifest file

• A sample manifest file

©Roi Yehoshua, 201288

CACHE MANIFEST

#Offline cache v1 #html files

article.html

#css filesassets/styles.css

#js filesassets/javascript.js

#imagesassets/ico_ninja-star.gif

CACHE MANIFEST

#Offline cache v1 #html files

article.html

#css filesassets/styles.css

#js filesassets/javascript.js

#imagesassets/ico_ninja-star.gif

Page 89: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Manifest file

• Every page that needs to use the manifest must link to it, using the manifest attribute

©Roi Yehoshua, 201289

!< DOCTYPEhtml>< htmlmanifestcache.manifest/"=">

<head>< title/>Offline App<title>

/<head><body>/<body>/<html>

!<DOCTYPE html><html manifest="/cache.manifest">

<head>< title>Offline App</title>

/<head><body>/<body>/<html>

Page 90: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Workers• Web Workers allow for a multi-threaded execution of

JavaScript programs.• A WebWorker is a JavaScript script executed from an HTML

page that runs in the background, independently of other, user-interface scripts that may also have been executed from the same HTML page.

• Can be used to perform a computationally expensive task without interrupting the user interface.

• Web workers are currently supported by Safari, Chrome, Operaand Mozilla Firefox

• IE 10 added support for Web Workers in Platform Preview 2 ©Roi Yehoshua, 201290

Page 91: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Workers• Web workers interact with the document via message

passing. • The following code loads a JavaScript file

• To send message to the worker, use the postMessage() method of the worker object

©Roi Yehoshua, 201291

var worker = new Worker("worker_script.js"); var worker = new Worker("worker_script.js");

worker.postMessage("Hello World!");worker.postMessage("Hello World!");

Page 92: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Workers

• The event onmessage is used to retrieve information in the worker

©Roi Yehoshua, 201292

worker.onmessage = function (event){ )alert" Received message"(event.data + ;

doSomething;()} functiondoSomething { ()

//do work )worker.postMessage"!Work done"(;

}

worker.onmessage = function (event){ alert("Received message " + event.data);

doSomething;()} function doSomething{ ()

//do work worker.postMessage("Work done!");

}

Page 93: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Workers Limitations

©Roi Yehoshua, 201293

Page 94: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Sockets• WebSocket is a technology providing for bi-

directional, full-duplex communications channels, over a single TCP socket.

• It is designed to be implemented in web browsers and web servers, but it can be used by any client or server application.

• Chrome 14, Firefox 7 and Internet Explorer 10 are currently the only browsers supporting the latest draft specification ("hybi-10") of the WebSocket protocol.

©Roi Yehoshua, 201294

Page 95: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Sockets• Needs a dedicated server supporting web sockets• Server-Side implementations:

• Socket.IO, Jetty (Java), Ruby, Python, Perl• Client Side: Native support on iPhone.• Full Solution: Socket.IO.

• socket.io also provides a lot of extra functionality over existing web sockets

©Roi Yehoshua, 201295

Page 96: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Web Sockets Client

©Roi Yehoshua, 201296

var connection = new WebSocket('ws://foo.org/wall');connection.onopen = function () { connection.send('Ping');};

connection.onerror = function (error) { console.log('WebSocket Error ' + error);};

connection.onmessage = function (e) { console.log('Server: ' + e.data);

}; 

var connection = new WebSocket('ws://foo.org/wall');connection.onopen = function () { connection.send('Ping');};

connection.onerror = function (error) { console.log('WebSocket Error ' + error);};

connection.onmessage = function (e) { console.log('Server: ' + e.data);

}; 

Page 97: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

CSS3

• Like HTML5, CSS3 is a living standard• No unified standard yet• W3C has split the spec into modules• Each has its own timeline

• CSS3 Modules Recommendation Status• http://www.css3.info/modules/

Page 98: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

CSS3 New Features

• Improved Selectors• Border Radius• Box and Text Shadow• RGBA color• Multiple Columns• Box Resizing• Gradients• Transitions• Transforms• Media Queries

Page 99: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

CSS3 Media Queries

• You can query device dimensions:

• You can also query device orientation:

©Roi Yehoshua, 201299

/* Landscape smart phone */@media (min-width: 321px) and (max-width: 480px){ /* style goes here */}

/* Landscape smart phone */@media (min-width: 321px) and (max-width: 480px){ /* style goes here */}

@media (orientation:portrait){ /* style goes here */}

@media (orientation:portrait){ /* style goes here */}

Page 100: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

CSS3 Media Queries

• You can also query device pixel density

100

#header{ :backgroundurl(medium-density-image.png);

}@media (-webkit-device-pixel-ratio: 1.5){

*/CSS for high-density screens/* #header{

:backgroundurl(high-density-image.png);} }

@media (-webkit-device-pixel-ratio: 0.75){ */CSS for low-density screens/*

#header{ :backgroundurl(low-density-image.png);

} }

#header{ background:url(medium-density-image.png);

}@media (-webkit-device-pixel-ratio: 1.5){

*/CSS for high-density screens/* #header{

background:url(high-density-image.png);} }

@media (-webkit-device-pixel-ratio: 0.75){ */CSS for low-density screens/*

#header{ background:url(low-density-image.png);

} }

Page 101: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

CSS3 Media Queries

• It is also possible to use completely different CSS files– The following example links to different CSS file

dependent on the device’s pixel density

©Roi Yehoshua, 2012101

< linkrel "stylesheet"=media-webkit-device-pixel-)"= "(ratio: 1.5hrefhdpi.css"=>/ "

< linkrel "stylesheet"=media-webkit-device-pixel-)"= "(ratio: 1.0hrefmdpi.css"=>/ "

< linkrel "stylesheet"=media-webkit-device-pixel-)"= "(ratio: 0.75hrefldpi.css"=>/ "

<link rel="stylesheet" media="(-webkit-device-pixel-ratio: 1.5)" href="hdpi.css>/ "

<link rel="stylesheet" media="(-webkit-device-pixel-ratio: 1.0)" href="mdpi.css>/ "

<link rel="stylesheet" media="(-webkit-device-pixel-ratio: 0.75)" href="ldpi.css>/ "

Page 102: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Responsive Web Design

• Responsive Web Design (RWD) essentially indicates that a web site is crafted to use CSS3 media queries with fluid proportion-based grids, to adapt the layout to the viewing environment, and probably also flexible images.

• As a result, users across a broad range of devices and browsers will have access to a single source of content, laid out so as to be easy to read and navigate with a minimum of resizing, panning and scrolling.

©Roi Yehoshua, 2012102

Page 103: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Responsive Web Design• In the following example, we are going to adapt

the layout of a simple web page that contains a banner, a main content area and a side bar with 3 news items to different screen sizes and orientations

• We will need to classify the page into one of the following 4 types of screens:– Desktop or tablet landscape mode– Tablet portrait mode– Smartphone landscape mode– Smartphone portrait mode ©Roi Yehoshua, 2012103

Page 104: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The HTML Page (1)

104

<!DOCTYPE html><html><head> <title>Untitled Page</title> <meta name="viewport" content="width=device-width, initial-scale" /> <link rel="Stylesheet" href="style.css" /> </head><body> <div id="page1"> <div id="banner"> <img src="sky.gif" /> </div> <aside id="newsContainer"> <article class="newsClass"> <header class="newsTitle"> Article1 Header </header> <div class="newsContent"> .. </div> </article> <article class="newsClass"> … </article> <article class="newsClass"> … </article> </aside>

<!DOCTYPE html><html><head> <title>Untitled Page</title> <meta name="viewport" content="width=device-width, initial-scale" /> <link rel="Stylesheet" href="style.css" /> </head><body> <div id="page1"> <div id="banner"> <img src="sky.gif" /> </div> <aside id="newsContainer"> <article class="newsClass"> <header class="newsTitle"> Article1 Header </header> <div class="newsContent"> .. </div> </article> <article class="newsClass"> … </article> <article class="newsClass"> … </article> </aside>

Page 105: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

The HTML Page (2)

105

> section idmainContent"=<" >p<

… />p<

>p< …

/>p< >p<

… />p<

/>section< />div<

/>body<

> section id="mainContent<" >p<

… />p<

>p< …

/>p< >p<

… />p<

/>section< />div<

/>body<

Page 106: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Desktop Styling

106

/* Desktop and Tablet landscape styling */#page1{ width: 1000px; margin: 0 auto; font-family: Verdana;}#banner img{ max-width: 100%; /* adjust the image size to the page's width */}#newsContainer{ width: 30%; float: right;}#mainContent{ width: 68%;}

/* Desktop and Tablet landscape styling */#page1{ width: 1000px; margin: 0 auto; font-family: Verdana;}#banner img{ max-width: 100%; /* adjust the image size to the page's width */}#newsContainer{ width: 30%; float: right;}#mainContent{ width: 68%;}

Page 107: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Desktop Styling

107

.newsClass{ border: 1px solid black; margin: 5px;}.newsTitle{ background-color: #CCC; font-weight: bold; padding: 5px;}.newsContent{ padding: 5px;}

.newsClass{ border: 1px solid black; margin: 5px;}.newsTitle{ background-color: #CCC; font-weight: bold; padding: 5px;}.newsContent{ padding: 5px;}

Page 108: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

108

Page 109: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Tablet Styling

109

*/Tablet portrait styling/* @mediaand (max-width: 768px) (min-width: 480px)

{# page1

{ width :720px;

} }

*/Tablet portrait styling/* @media (min-width: 480px) and (max-width: 768px)

{# page1

{ width: 720px;

} }

Page 110: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

110

Page 111: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Smartphone Landscape Styling

111

*/Smartphone landscape styling/* @mediaand (max-width: 480px) (min-width: 320px)

{# page1

{ width :440px;

} # newsContainer

{ width :100%;

} . newsContent

{ display :none;

} . newsClass

{ float :left;

width :30%; }

# mainContent{

width :100%;} }

*/Smartphone landscape styling/* @media (min-width: 320px) and (max-width: 480px)

{# page1

{ width: 440px;

} # newsContainer

{ width: 100%;

} . newsContent

{ display: none;

} . newsClass

{ float: left;

width: 30%; }

# mainContent{

width: 100%;} }

Page 112: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Smartphone Landscape Styling

112

Page 113: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Smartphone Portrait Styling

113

/* Smartphone portrait styling */@media (max-width: 320px){ #page1 {

width: 280px; }  #newsContainer {

width: 100%; }  .newsContent {

display: none; }  .newsClass {

float: left;width: 28%;margin: 2px;

}  #mainContent {

width: 100%; }}

/* Smartphone portrait styling */@media (max-width: 320px){ #page1 {

width: 280px; }  #newsContainer {

width: 100%; }  .newsContent {

display: none; }  .newsClass {

float: left;width: 28%;margin: 2px;

}  #mainContent {

width: 100%; }}

Page 114: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Smartphone Portrait Styling

©Roi Yehoshua, 2012114

Page 115: Lecturer: Roi Yehoshua roiyeho@gmail.com HTML5 Open Day 05/09/2012

Thank You!

• Follow me on Facebook to get news and updates on Mobile Application Development

• http://www.facebook.com/RoiYehoshuaMobileApp

Roi [email protected]

©Roi Yehoshua, 2012115