Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecturer: Roi Yehoshua HTML5 Open Day 05/09/2012.

Similar presentations


Presentation on theme: "Lecturer: Roi Yehoshua HTML5 Open Day 05/09/2012."— Presentation transcript:

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

2 Agenda HTML 5.0 Introduction Overview of HTML5 new features Overview of CSS3 capabilities and new features © Roi Yehoshua, 20122

3 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

4 HTML Timeline © Roi Yehoshua, 20124

5 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

6 HTML5 New Features New structural elements Canvas and 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

7 HTML5 Desktop Browser Support © Roi Yehoshua, 2012 7

8 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

9 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

10 One codebase, all platforms © Roi Yehoshua, 201210

11 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

12 Real-World jQM © Roi Yehoshua, 201212 http://www.jqmgallery.com/

13 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

14 Hybrid Apps © Roi Yehoshua, 201214

15 PhoneGap Selected Apps © Roi Yehoshua, 201215

16 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 information about service/business M-Commerce (Mobile online shop) Simple games Photo taking app 3D or complex games

17 HTML5 Editors HTML5 Open Source Editors Komodo Edit http://www.activestate.com/komodo-edithttp://www.activestate.com/komodo-edit Maquetta, IBM’s open source WYSIWYG HTML5 Editor http://maqetta.org/ 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-53f6cdc2cd83http://visualstudiogallery.msdn.microsoft.com/a15c3ce9- f58f-42b7-8668-53f6cdc2cd83 © Roi Yehoshua, 201217

18 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 and tags © Roi Yehoshua, 201218

19 Basic HTML5 Page © Roi Yehoshua, 201219 My Amazing Page alert("Hello there"); This is my first HTML5 page My Amazing Page alert("Hello there"); This is my first HTML5 page

20 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: © Roi Yehoshua, 201220

21 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

22 Using Canvas The 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 var canvas = document.getElementById("myCanvas"); var context = canvas.getContext(“2d"); context.fillRect(25, 25, 150, 100);

23 Drawing Rectangle example © Roi Yehoshua, 201223 function drawRect() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.fillStyle = "blue"; context.fillRect(25, 25, 150, 100); } Update your browser to enjoy canvas! function drawRect() { var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); context.fillStyle = "blue"; context.fillRect(25, 25, 150, 100); } Update your browser to enjoy canvas!

24 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(); }

25 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); }; }

26 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

27 Canvas Image Filtering © Roi Yehoshua, 201227 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(); } 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(); }

28 Canvas Image Filtering © Roi Yehoshua, 201228 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; } 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; }

29 Canvas Image Filtering © Roi Yehoshua, 201229

30 Games created with Canvas A first person shooter http://www.benjoffe.com/code/de mos/canvascape/textureshttp://www.benjoffe.com/code/de mos/canvascape/textures Asteroids http://www.kevs3d.co.uk/dev/aster oids/http://www.kevs3d.co.uk/dev/aster oids/ Other games http://savedelete.com/best-html5- canvas-games.htmlhttp://savedelete.com/best-html5- canvas-games.html © Roi Yehoshua, 201230

31 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

32 Embedding SVG in HTML5 HTML5 allows embedding SVG directly using the tag © Roi Yehoshua, 201232 SVG HTML5 SVG Circle SVG HTML5 SVG Circle

33 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

34 HTML5 Multimedia Multimedia support has always been a delivery issue Commonly the tag provided the support With a classid attribute to denote the plugin required The non-standard 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

35 HTML5 Video The 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 add legacy support © Roi Yehoshua, 201235 Your browser fights the future! Your browser fights the future!

36 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

37 The Source element Media must be supported in multiple formats The element gives multiple chances Use instead of src attribute on video tag © Roi Yehoshua, 201237

38 Video API 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(); }

39 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

40 Video API Demo http://www.w3.org/2010/05/video/mediaevents.html © Roi Yehoshua, 201240

41 HTML5 Audio Almost identical to the video element source elements need to be used © Roi Yehoshua, 201241 Your browser doesn't support HTML5 Audio Your browser doesn't support HTML5 Audio

42 Combining Canvas with Video Effects http://www.craftymind.com/factory/html5video/CanvasVideo.htmlhttp://www.craftymind.com/factory/html5video/CanvasVideo.html © Roi Yehoshua, 201242

43 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

44 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

45 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

46 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")); localStorage.thing = 5; var x = parseInt(localStorage.thing); localStorage.thing = 5; var x = parseInt(localStorage.thing);

47 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

48 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

49 JSON and JavaScript © Roi Yehoshua, 2012 49 JSON is a subset of the object literal notation of JavaScript –Can be used in the JS language with no problems var 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" Can use dot or subscript operators to access members

50 JSON Serialization © Roi Yehoshua, 2012 50 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)

51 JSON Serialization © Roi Yehoshua, 2012 51 localStorage.products = JSON.stringify(products); var p = JSON.parse(localStorage.products); localStorage.products = JSON.stringify(products); var p = JSON.parse(localStorage.products);

52 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) { });

53 Web SQL Web SQL gives us the ability to create a real database client side Using SQLite (http://sqlite.org)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

54 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);

55 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]); });

56 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) { var len = 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); } });

57 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

58 New Input Elements HTML5 adds 13 new type options Mostly extend the tags with new type values If a browser doesn’t understand, the extension is rendered as No requirement in the spec for how browsers present Different browsers show different UI and error messages © Roi Yehoshua, 201258

59 HTML5 Forms Browser Support © Roi Yehoshua, 201259

60 New Input Elements HTML5 adds 13 new type options Mostly extend the tags with new type values If a browser doesn’t understand, the extension is rendered as No requirement in the spec for how browsers present Different browsers show different UI and error messages © Roi Yehoshua, 201260

61 Email Input Type Add type value of 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, 2012 61

62 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, 2012 62

63 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, 2012 63

64 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, 2012 64

65 Date Input Type © Roi Yehoshua, 2012 65 In Chrome In Opera

66 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, 2012 66

67 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, 2012 67

68 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, 2012 68

69 Pattern Validations You can use the pattern attribute to specify your own custom regular expression. © Roi Yehoshua, 2012 69

70 Custom Validation Messages You can set a custom validation message using the method element.setCustomValidity(message) © Roi Yehoshua, 2012 70 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(""); }

71 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, 2012 71 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(""); }

72 Styling with CSS3 © Roi Yehoshua, 2012 72 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; } E-mail: 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; } E-mail:

73 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, 2012 73 { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/13/4035603/slides/slide_73.jpg", "name": "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, 2012 73

74 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, 2012 74

75 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, 2012 75 navigator.geolocation.getCurrentPosition(showLocation, handleLocationError);

76 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, 2012 76 function showLocation(position) { var lat = position.coords.latitude; var long = position.coords.longitude; var when = position.timestamp; } function showLocation(position) { var lat = position.coords.latitude; var long = position.coords.longitude; var when = position.timestamp; }

77 Coords object Only latitude, longitude and accuracy are guaranteed Depends on device whether the other are supported © Roi Yehoshua, 2012 77 PropertyTypeDescription latitudedoubleDecimal degrees longitudedoubleDecimal degrees altitudedouble or nullMeters above the referenced ellipsoid accuracydoubleMeters altitudeAccuracydouble or nullMeters headingdouble or nullDegrees clockwise from true north speeddouble or nullMeters/second

78 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, 2012 78 navigator.geolocation.watchPosition(success, error);

79 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/do cumentation/javascript/ http://code.google.com/apis/maps/do cumentation/javascript/ © Roi Yehoshua, 2012 79

80 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, 2012 80

81 Google Maps API © Roi Yehoshua, 2012 81 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); }

82 Update Location on Map © Roi Yehoshua, 2012 82 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); } 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); }

83 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, 2012 83 function drawMarker(latlng) { marker = new ns.Marker({ position: latlng, map: map, title: 'You are here!' }); } function drawMarker(latlng) { marker = new ns.Marker({ position: latlng, map: map, title: 'You are here!' }); }

84 Markers © Roi Yehoshua, 2012 84

85 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, 2012 85

86 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, 2012 86

87 Manifest File © Roi Yehoshua, 2012 87

88 Manifest file A sample manifest file © Roi Yehoshua, 2012 88 CACHE MANIFEST # Offline cache v1 # html files article.html # css files assets/styles.css # js files assets/javascript.js # images assets/ico_ninja-star.gif CACHE MANIFEST # Offline cache v1 # html files article.html # css files assets/styles.css # js files assets/javascript.js # images assets/ico_ninja-star.gif

89 Manifest file Every page that needs to use the manifest must link to it, using the manifest attribute © Roi Yehoshua, 2012 89 Offline App Offline App

90 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, 2012 90

91 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, 2012 91 var worker = new Worker("worker_script.js"); worker.postMessage("Hello World!");

92 Web Workers The event onmessage is used to retrieve information in the worker © Roi Yehoshua, 2012 92 worker.onmessage = function (event) { alert("Received message " + event.data); doSomething(); } function doSomething() { //do work worker.postMessage("Work done!"); } worker.onmessage = function (event) { alert("Received message " + event.data); doSomething(); } function doSomething() { //do work worker.postMessage("Work done!"); }

93 Web Workers Limitations © Roi Yehoshua, 2012 93

94 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

95 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, 2012 95

96 Web Sockets Client © Roi Yehoshua, 2012 96 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); };

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

98 CSS3 New Features Improved Selectors Border Radius Box and Text Shadow RGBA color Multiple Columns Box Resizing Gradients Transitions Transforms Media Queries

99 CSS3 Media Queries You can query device dimensions: You can also query device orientation: © Roi Yehoshua, 2012 99 /* 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 */ }

100 CSS3 Media Queries You can also query device pixel density 100 #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); } #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); }

101 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, 2012 101

102 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, 2012 102

103 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, 2012 103

104 The HTML Page (1) 104 Untitled Page Article1 Header.. … … Untitled Page Article1 Header.. … …

105 The HTML Page (2) 105 … … … … … …

106 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%; }

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

108 108

109 Tablet Styling 109 /* Tablet portrait styling */ @media (min-width: 480px) and (max-width: 768px) { #page1 { width: 720px; } /* Tablet portrait styling */ @media (min-width: 480px) and (max-width: 768px) { #page1 { width: 720px; }

110 110

111 Smartphone Landscape Styling 111 /* 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%; } /* 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%; }

112 Smartphone Landscape Styling 112

113 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%; }

114 Smartphone Portrait Styling © Roi Yehoshua, 2012114

115 Thank You! Follow me on Facebook to get news and updates on Mobile Application Development http://www.facebook.com/RoiYehoshuaMobile Apphttp://www.facebook.com/RoiYehoshuaMobile App Roi Yehoshua roiyeho@gmail.com © Roi Yehoshua, 2012115


Download ppt "Lecturer: Roi Yehoshua HTML5 Open Day 05/09/2012."

Similar presentations


Ads by Google