Lecturer: Roi Yehoshua 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
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
HTML Timeline © Roi Yehoshua, 20124
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
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
HTML5 Desktop Browser Support © Roi Yehoshua,
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
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
One codebase, all platforms © Roi Yehoshua,
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 (July 2012) © Roi Yehoshua,
Real-World jQM © Roi Yehoshua,
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,
Hybrid Apps © Roi Yehoshua,
PhoneGap Selected Apps © Roi Yehoshua,
Web vs. Native © Roi Yehoshua, 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
HTML5 Editors HTML5 Open Source Editors Komodo Edit Maquetta, IBM’s open source WYSIWYG HTML5 Editor 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 f58f-42b f6cdc2cd83http://visualstudiogallery.msdn.microsoft.com/a15c3ce9- f58f-42b f6cdc2cd83 © Roi Yehoshua,
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,
Basic HTML5 Page © Roi Yehoshua, My Amazing Page alert("Hello there"); This is my first HTML5 page My Amazing Page alert("Hello there"); This is my first HTML5 page
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,
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,
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, var canvas = document.getElementById("myCanvas"); var context = canvas.getContext(“2d"); context.fillRect(25, 25, 150, 100);
Drawing Rectangle example © Roi Yehoshua, 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!
Drawing Paths Example © Roi Yehoshua, 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(); }
Drawing Images Example © Roi Yehoshua, 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); }; }
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,
Canvas Image Filtering © Roi Yehoshua, 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(); }
Canvas Image Filtering © Roi Yehoshua, 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; }
Canvas Image Filtering © Roi Yehoshua,
Games created with Canvas A first person shooter mos/canvascape/textureshttp:// mos/canvascape/textures Asteroids oids/ oids/ Other games canvas-games.htmlhttp://savedelete.com/best-html5- canvas-games.html © Roi Yehoshua,
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,
Embedding SVG in HTML5 HTML5 allows embedding SVG directly using the tag © Roi Yehoshua, SVG HTML5 SVG Circle SVG HTML5 SVG Circle
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,
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,
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, Your browser fights the future! Your browser fights the future!
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,
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,
Video API element can be controlled via JavaScript Used to give a consistent cross browser feel Or dynamic functionality © Roi Yehoshua, 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(); }
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,
Video API Demo © Roi Yehoshua,
HTML5 Audio Almost identical to the video element source elements need to be used © Roi Yehoshua, Your browser doesn't support HTML5 Audio Your browser doesn't support HTML5 Audio
Combining Canvas with Video Effects © Roi Yehoshua,
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,
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,
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,
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, 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);
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,
Dealing with Complex Objects AJAX applications often hold JSON data structures Using a JSON serialization we can add it to local storage © Roi Yehoshua,
JSON and JavaScript © Roi Yehoshua, 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
JSON Serialization © Roi Yehoshua, 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 (
JSON Serialization © Roi Yehoshua, localStorage.products = JSON.stringify(products); var p = JSON.parse(localStorage.products); localStorage.products = JSON.stringify(products); var p = JSON.parse(localStorage.products);
Get JSON from Server © Roi Yehoshua, $.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) { });
Web SQL Web SQL gives us the ability to create a real database client side Using SQLite ( 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,
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, var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
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, 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]); });
Execute SQL To select values from the table, you can use a callback to capture the results: © Roi Yehoshua, 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); } });
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,
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,
HTML5 Forms Browser Support © Roi Yehoshua,
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,
Input Type Add type value of 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,
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,
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,
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,
Date Input Type © Roi Yehoshua, In Chrome In Opera
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,
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,
Type Validations Using the new HTML5 input fields, you can explicitly create inputs for things like numbers, 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,
Pattern Validations You can use the pattern attribute to specify your own custom regular expression. © Roi Yehoshua,
Custom Validation Messages You can set a custom validation message using the method element.setCustomValidity(message) © Roi Yehoshua, function check(input) { if (!input.checkValidity()) { input.setCustomValidity("Dude '" + input.value + "' is not a valid . Enter something nice!!"); } else { input.setCustomValidity(""); } function check(input) { if (!input.checkValidity()) { input.setCustomValidity("Dude '" + input.value + "' is not a valid . Enter something nice!!"); } else { input.setCustomValidity(""); }
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, 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(""); }
Styling with CSS3 © Roi Yehoshua, input[type=text]:focus:valid, input[type= ]:focus:valid, input[type=number]:focus:in-range { outline: 2px green solid; } input[type=text]:focus:invalid, input[type= ]:focus:invalid, input[type=number]:focus:out-of-range { outline: 2px red solid; } input[type=text]:focus:valid, input[type= ]:focus:valid, input[type=number]:focus:in-range { outline: 2px green solid; } input[type=text]:focus:invalid, input[type= ]:focus:invalid, input[type=number]:focus:out-of-range { outline: 2px red solid; }
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, <input type="text" id="name" name="name" placeholder="First and last name" <input type="text" id="name" name="name" placeholder="First and last name"
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,
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, navigator.geolocation.getCurrentPosition(showLocation, handleLocationError);
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, 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; }
Coords object Only latitude, longitude and accuracy are guaranteed Depends on device whether the other are supported © Roi Yehoshua, 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
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, navigator.geolocation.watchPosition(success, error);
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: cumentation/javascript/ cumentation/javascript/ © Roi Yehoshua,
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,
Google Maps API © Roi Yehoshua, 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); }
Update Location on Map © Roi Yehoshua, 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); }
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, 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!' }); }
Markers © Roi Yehoshua,
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,
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,
Manifest File © Roi Yehoshua,
Manifest file A sample manifest file © Roi Yehoshua, 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
Manifest file Every page that needs to use the manifest must link to it, using the manifest attribute © Roi Yehoshua, Offline App Offline App
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,
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, var worker = new Worker("worker_script.js"); worker.postMessage("Hello World!");
Web Workers The event onmessage is used to retrieve information in the worker © Roi Yehoshua, 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!"); }
Web Workers Limitations © Roi Yehoshua,
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,
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,
Web Sockets Client © Roi Yehoshua, 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); };
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
CSS3 New Features Improved Selectors Border Radius Box and Text Shadow RGBA color Multiple Columns Box Resizing Gradients Transitions Transforms Media Queries
CSS3 Media Queries You can query device dimensions: You can also query device orientation: © Roi Yehoshua, /* Landscape smart phone (min-width: 321px) and (max-width: 480px) { /* style goes here */ } /* Landscape smart phone (min-width: 321px) and (max-width: 480px) { /* style goes here */ (orientation:portrait) { /* style goes here */ (orientation:portrait) { /* style goes here */ }
CSS3 Media Queries You can also query device pixel density 100 #header { background:url(medium-density-image.png); (-webkit-device-pixel-ratio: 1.5) { /* CSS for high-density screens */ #header { background:url(high-density-image.png); (-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); (-webkit-device-pixel-ratio: 1.5) { /* CSS for high-density screens */ #header { background:url(high-density-image.png); (-webkit-device-pixel-ratio: 0.75) { /* CSS for low-density screens */ #header { background:url(low-density-image.png); }
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,
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,
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,
The HTML Page (1) 104 Untitled Page Article1 Header.. … … Untitled Page Article1 Header.. … …
The HTML Page (2) 105 … … … … … …
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%; }
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
Tablet Styling 109 /* Tablet portrait styling (min-width: 480px) and (max-width: 768px) { #page1 { width: 720px; } /* Tablet portrait styling (min-width: 480px) and (max-width: 768px) { #page1 { width: 720px; }
110
Smartphone Landscape Styling 111 /* Smartphone landscape styling (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 (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 112
Smartphone Portrait Styling 113 /* Smartphone portrait styling (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 (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 © Roi Yehoshua,
Thank You! Follow me on Facebook to get news and updates on Mobile Application Development Apphttp:// App Roi Yehoshua © Roi Yehoshua,