SlideShare una empresa de Scribd logo
1 de 125
Descargar para leer sin conexión
HTML5 APIs
Tuesday, February 26, 13
Web Tech History
                   1991 HTML

                   1994 HTML2

                   1996 CSS1 + JavaScript

                   1997 HTML4

                   1998 CSS2

                   2000 XHTML1

                   2002 Tableless Web Design

                   2005 Ajax

                   2009 HTML5




Tuesday, February 26, 13
HTML5 What


                   Syntactical Features (audio, video)

                   Semantical Features (section, article)

                   New APIs




Tuesday, February 26, 13
HTML5 How

                   Progressive Enhancements

                   Existing web sites can move to HTML5

                   Old browsers will still be able to use the page

                   Modernizr: http://www.modernizr.com/




Tuesday, February 26, 13
HTML5 New APIs
                   Web Storage            Geolocation

                   Web SQL                Device Orientation

                   Application Cache      Form Enhancements

                   Web Workers            Audio, Video

                   Web Socket             Canvas

                   Desktop Notifications   Web GL

                   Drag & Drop            History API

                   File System API        And More...



Tuesday, February 26, 13
Modernizr: Before We
                   Begin

                   Script Loader

                   Feature Detector




Tuesday, February 26, 13
Hello Modernizr
        Modernizr.load({
          test: 3 > 5,

          yep : 'http://code.jquery.com/
        jquery-1.9.1.min.js',

          nope: 'http://cdnjs.cloudflare.com/
        ajax/libs/zepto/1.0rc1/zepto.min.js'
        });



Tuesday, February 26, 13
More Loader Features

                   Specify only “yep” or “nope”

                   Provide array

                   Complete callback

                   Demo: http://jsbin.com/abowap/2/edit




Tuesday, February 26, 13
polyfill (n):
                               a JavaScript
                    shim that replicates the
                    standard API for older
                    browsers


Tuesday, February 26, 13
Feature Detection

                   Modernizr.applicationcache

                   Modernizr.canvas

                   Modernizr.audio

                   Modernizr.inputtypes

                   Demo: http://jsbin.com/abowap/3/edit



Tuesday, February 26, 13
Feature Detection +
                   Polyfill

       Modernizr.load({
           test: Modernizr.input.placeholder,
           nope: [
                   'placeholder_polyfill.min.css',
                   'placeholder_polyfill.jquery.min.combo.js'
                 ]
       });




Tuesday, February 26, 13
Q&A



Tuesday, February 26, 13
Offline Storage




                    Work Offline   Store Persistent State




Tuesday, February 26, 13
Local Data Storage


                   How do you store data on a client’s machine ?




Tuesday, February 26, 13
Cookies ?




Tuesday, February 26, 13
Server   Client




Tuesday, February 26, 13
Local Storage
                   Before HTML5: cookies were used to store data
                   on the client side

                   Cookies Disadvantages:

                           Limited size (4k)

                           Sent with every request

                           Complex to use



Tuesday, February 26, 13
Local Storage
                   A JavaScript API for
                   storing client side data

                   Can store up to 5MB
                   (per site)

                   Simple API

                   Never run out of space



Tuesday, February 26, 13
Local Storage

                   Store Data
                   window.localStorage.setItem(“key”, “value”);


                   Read Data
                   window.localStorage.getItem(“key”);


                   Remove Data
                   window.localStorage.removeItem(“key”);




Tuesday, February 26, 13
Local Storage

                   Can also use direct access on the storage object,
                   so this code also works:

                   window.localStorage.username = “Jimmy”;
                   var username = window.localStorage.username;

                   console.log(‘Hello ‘ + username);




Tuesday, February 26, 13
Local Storage

                   Methods:
                           clear()

                           key(idx)

                           length()




Tuesday, February 26, 13
Session Storage

                   Interface is the same as localStorage

                   Lifetime is only for the current browser window or
                   tab (or browser session)

                   Best used for temporary preferences that should
                   not be shared between tabs




Tuesday, February 26, 13
Storage Lab

                   We’ll implement an address book app

                   Keeps a list of contacts info: name, phone number,
                   email

                   Provide add/view/delete contacts




Tuesday, February 26, 13
Storage Lab
                   Use the starter:
                   https://github.com/ynonp/advanced-fed-
                   examples/tree/master/contacts




Tuesday, February 26, 13
Offline Web App

                   Online-Offline Apps

                   Sync with the Cloud, but can suffer a downtime
                   (Think Google Gears)

                   Can run completely offline app as a standalone

                   Mobile - Save bandwidth




Tuesday, February 26, 13
Offline Web App
                            GET MANIFEST


                           CACHE MANIFEST
                           index.html
                           style/main.css
                           script/main.js




Tuesday, February 26, 13
Cache Manifest File


                   Lists all the files that should be stored for offline
                   access

                   Enable with:
                   <html manifest="example.appcache">




Tuesday, February 26, 13
example.appcache

                                           CACHE MANIFEST
                   Required header
                                           index.html
                   CACHE MANIFEST
                                           stylesheet.css
                   A list of cached files
                                           images/logo.png

                                           scripts/main.js




Tuesday, February 26, 13
Demo
             Caching A Website




Tuesday, February 26, 13
Offline Web App

                   The cache manifest is divided to sections, the
                   default is called CACHE

                   Every file listed in the default CACHE section will
                   be cached by the browser forever (or until
                   explicitly deleted by the user)




Tuesday, February 26, 13
Offline Web App


                   The NETWORK section lists files that should never
                   be cached

                   Best used for dynamic content (think gmail)




Tuesday, February 26, 13
Offline Web App

                   The FALLBACK section lists fallback content that
                   should be used if network is not available

                   So, if you’re trying to read a message while offline,
                   you can get a nice formatted error page




Tuesday, February 26, 13
Manifest Cache

                                      Cache the file locally,
                           CACHE
                                      never refresh


                                      Files should not be
                           NETWORK
                                      cached


                                      Cache a fallback
                           FALLBACK
                                      content



Tuesday, February 26, 13
Offline App Exercise

                   A Dynamic reader with two pages

                   First lists available articles, the second displays a
                   given article

                   Use your favorite server side technology and jQM

                   Which files do you put in each manifest section ?




Tuesday, February 26, 13
Manifest - The Good

                   Can store any file
                   locally

                   Provides offline/online
                   app functionality

                   Transparent to the user




Tuesday, February 26, 13
Manifest - The Bad


                   Not suitable for data
                   storage

                   Complex update logic




Tuesday, February 26, 13
Web SQL

                   The final storage option for offline apps is the Web
                   SQL

                   Allows using a local database to better store
                   relational data

                   Best suited for hierarchical lists apps




Tuesday, February 26, 13
Q&A

                   Storage

                   Geo Location

                   Video

                   Canvas




Tuesday, February 26, 13
Geo Location

                   Detect where your user
                   is now

                   Show nearby places

                   Display location aware
                   data




Tuesday, February 26, 13
Technologies

                   GPS

                   A-GPS

                   Cell Information

                   WiFi Positioning




Tuesday, February 26, 13
GPS
                   Global Positioning
                   System

                   Accuracy error: 2-10m

                   Requires clear sky view

                   Time to position:
                   5 seconds - 5 minutes



Tuesday, February 26, 13
A-GPS

                   Uses both GPS chip
                   and network
                   information to get
                   location

                   Much faster to get
                   location




Tuesday, February 26, 13
Cell Information
                   Uses cell towers to
                   calculate a device’s
                   location

                   Accuracy: A block or
                   up to some km

                   Time to location:
                   immediate



Tuesday, February 26, 13
WiFi Positioning

                   Detect location using a
                   list of wireless routers
                   in your area

                   Relies on existing
                   router databases




Tuesday, February 26, 13
Location API


                   Supported Platforms:

                           iPhone 3.0+

                           Android 2.0+




Tuesday, February 26, 13
Location API

                   function get_location() {
                     navigator.geolocation.getCurrentPosition(show_map);
                   }

                   function show_map(position) {
                     var lat = position.coords.latitude;
                     var long = position.coords.longitude;
                     var when = position.timestamp;
                     // show me the map
                   }




Tuesday, February 26, 13
Location API

                   navigator.geolocation is the entry point for
                   all location related calls

                   Location querying is async, so a callback is
                   supplied

                   User will be asked permission to share location




Tuesday, February 26, 13
Location API


                   iPhone browser asks
                   user permissions
                   before sharing location




Tuesday, February 26, 13
Location API

                   Location API uses
                   callbacks to perform
                   error handling

                   When working with
                   location, always
                   consider errors




Tuesday, February 26, 13
Location API

                   getCurrentPosition(

                           successCallback,

                           optional errorCallback,

                           optional config

                   );




Tuesday, February 26, 13
The Coord object
                   coords.latitude

                   coords.longitude

                   coords.altitude

                   coords.accuracy

                   coords.altitudeAccuracy

                   coords.heading

                   coords.speed

                   timestamp




Tuesday, February 26, 13
The Coord Object

                   Not all fields will be available at all times

                   Sizes are specified in meters and degrees

                   timestamp is a DOMTimestamp (acts like a Date
                   object)




Tuesday, February 26, 13
Location Config
                   last parameter to getCurrentPosition is a config
                   object

                   there are 3 configuration options available:

                           timeout

                           maximumAge

                           enableHighAccuracy



Tuesday, February 26, 13
Using Config

                   window.navigator.geolocation.getCurrentPosition(
                     successCallback,
                     failureCallback,
                                                              How long to wait before giving up
                           { timeout            : 0,                      (in ms)


                             maximumAge         : 60000,       Try to use a cached value aged
                                                                            (in ms)


                             enableHighAccuracy : false });        Use the most accurate
                                                                    positioning method




Tuesday, February 26, 13
Handle Errors

                   The errorCallback takes a single argument called
                   error object

                   The object has two fields:
                   error.code & error.message

                   Use error.message for debug only




Tuesday, February 26, 13
Next: The Map




Tuesday, February 26, 13
Show The Map

                   On the iPhone, a redirect to a google maps url
                   starts the map application

                   The Good: easy to use

                   The Bad:

                           user leaves the app




Tuesday, February 26, 13
Google Maps API

                   A JS API to display
                   embedded maps in
                   web sites

                   Works on both desktop
                   and mobile devices

                   (Almost) Free to use




Tuesday, February 26, 13
Google Maps API
                   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

                   Place markers on the map using
                   google.maps.Marker

                   Full documentation:
                   http://developer.google.com/apis/maps/
                   documentation/javascript/
Tuesday, February 26, 13
Google Maps API

                   Maps Workflow:

                           Choose a div

                           Create a new google.maps.Map(...)

                   Remember to set minimum height on the div




Tuesday, February 26, 13
Objects To Note

                   google.maps.LatLng - represents a latitude/
                   longitude pair

                   Methods:

                           lat() returns the lat value

                           lng() returns the long value




Tuesday, February 26, 13
Objects To Note

                   google.maps.Map( element, options )

                   Interesting Methods:

                           panBy( x, y ) - move the map by x,y

                           panTo( latlng ) - move the map to latlng

                           setZoom( zoom )



Tuesday, February 26, 13
Objects To Note
                   google.maps.MapOptions: configuration object

                   Interesting options

                           center: latlng

                           disableDefaultUI: boolean

                           draggable: boolean

                           mapTypeId: HYBRID, ROADMAP, SATELLITE


Tuesday, February 26, 13
Demo
             Show Location On Map




Tuesday, February 26, 13
Location Tracking


                   Receive notifications about location changes

                   Can use for navigation apps, sport apps, and more

                   Browser must remain open




Tuesday, February 26, 13
Location Tracking

                      use 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


Tuesday, February 26, 13
Exercise: Where’s My
                   Car
                   Write a parking reminder app

                   One button titled “parked” which marks current
                   location and keeps it in local storage

                   Another button titled “find” which shows a map
                   leading to your car

                   Keep data in local storage



Tuesday, February 26, 13
Q&A

                   Storage

                   Geo Location (iPhone, Android)

                   Video & Audio (iPhone, Android)

                   Canvas (iPhone, Android)




Tuesday, February 26, 13
VIDEO
    THE EASY WAY
Tuesday, February 26, 13
Video Tag

                           HTML5 introduces a <video> tag to embed
                           videos in a web page.

                           Different browsers support different video
                           formats. The <video> tag can specify multiple
                           formats.




Tuesday, February 26, 13
Video Formats
                   Video formats are like
                   languages

                   The same video can be
                   encoded in different
                   formats

                   A browser must “speak
                   the language” to be
                   able to play the video


Tuesday, February 26, 13
Video Converter

                   Miro is a free open
                   source video player
                   and converter

                   http://
                   www.getmiro.com




Tuesday, February 26, 13
Browser Support


                   HTML5 spec does not define a video codec to use

                   h.264 is the most widely supported. Plays on
                   iPhone and Android




Tuesday, February 26, 13
The Markup

                                            Poster image file name

                   <video poster=”star.png”>

                           <source src=”zebra.mp4” />
                                          Video file name. Usually mp4
                   </video>                    for mobile devices




Tuesday, February 26, 13
Limitations

                   Video will start playing in a dedicated “player”
                   window, when the user taps it

                   It is not possible to auto play the video on mobile

                   It is not possible to embed other content on the
                   video on mobile




Tuesday, February 26, 13
Audio Tag


                   Structured like a Video tag

                   iPhone and Android support MP3

                   No autoplay




Tuesday, February 26, 13
Lab
                   Audio SoundBoard

                   Use Animal Sounds:
                   http://apps.ynonperek.com/
                   audio.zip

                   Images: http://
                   apps.ynonperek.com/images.zip

                   Use starter:
                   https://github.com/ynonp/
                   mobileweb-examples/blob/
                   master/html5/SoundBoard/
                   audioboard_starter.html

Tuesday, February 26, 13
Q&A

                   Storage

                   Geo Location

                   Video & Audio

                   Canvas (iPhone, Android)




Tuesday, February 26, 13
CANVAS
Tuesday, February 26, 13
HTML5 Canvas
                   A 2d graphics canvas
                   for HTML apps

                   Games

                   Dynamic images

                   Client-side painting
                   (saves bandwidth)



Tuesday, February 26, 13
Hello Canvas


                   An HTML element <canvas> on the markup

                   JS code to do actual painting




Tuesday, February 26, 13
Hello Canvas

                   The canvas element has no content and no border
                   of its own

                   A canvas keeps a painting context on which we
                   perform the drawing

                   First example uses context.fillText()

                           examples/canvas/intro.html




Tuesday, February 26, 13
Basic Drawing

                   Context object provides the drawing functions.
                   Each takes coordinates and data.

                   Drawing style is determined by setting attributes
                   on the context object.

                   Most style properties are plain text strings




Tuesday, February 26, 13
Coordinate System




Tuesday, February 26, 13
Drawing Rectangles
                   Let’s start with drawing
                   rectangles                 fillRect(x, y, w, h)

                   note fillRect draws a       strokeRect(x, y, w, h)

                   filled rectangle, while     clearRect(x, y, w, h)
                   strokeRect draws just
                   the outline

                   fillStyle and strokeStyle
                   determine the colors


Tuesday, February 26, 13
Demo: Rects



Tuesday, February 26, 13
Drawing Paths

                   A composite shape on the canvas is called “path”

                   Paths are made of lines, arcs, curves and
                   rectangles

                   A path can be filled or stoked. Nothing is painted
                   until either fill() or stroke() is called




Tuesday, February 26, 13
Drawing Paths

                                            moveTo(x, y)
                   Lines are painted with
                   lineTo and moveTo        lineTo(x, y)

                   stroke() performs the
                   actual drawing




Tuesday, February 26, 13
Lines Example

          ctx.beginPath();
          ctx.strokeStyle = "hsl(249, 41%, 50%)";

          ctx.lineWidth = 6;
          ctx.moveTo(0, 0);
          ctx.lineTo(20, 10);
          ctx.lineTo(0, 20);
          ctx.stroke();




         Cool Color Selector:
         http://mothereffinghsl.com/

Tuesday, February 26, 13
Using The Image

                   It’s possible to use an image drawn in a canvas for
                   other elements

                   get the image url using:
                   canvas.toDataURL()

                   use image url as a source attribute of an img tag

                   Extra: draw on a hidden canvas



Tuesday, February 26, 13
Drawing Circles
                   use arc() and arcTo() to   arc(x, y, radius,
                   draw circles or parts of       startAngle,
                   them                           endAngle,
                                                  antiClockWise)
                   Degrees are specified
                   in radians.                arcTo(x1, y1,
                   Math.PI = 180 deg                x2, y2,
                                                    radius)
                   remember to fill() or
                   stroke()


Tuesday, February 26, 13
Exercise 1

                   Draw the image on the
                   right

                   Use moveTo and arc

                   Bonus: add colors




Tuesday, February 26, 13
Exercise 2

                   Draw the image on the
                   right

                   Place pins randomly
                   across the screen




Tuesday, February 26, 13
Advanced Canvas


                   Transformations

                   Image Filters




Tuesday, February 26, 13
Transformations

                   supported               translate(x, y)
                   transformations:
                   translation, scaling,   rotate(angle)
                   rotation                scale(x, y)
                   Transformations affect
                   all drawing code
                   performed after them




Tuesday, February 26, 13
Translation

                   Move the origin of the canvas to another point on
                   the canvas

                   The new point is now (0, 0)

                   This can make drawing code simpler




Tuesday, February 26, 13
Translation Example


                   Use translation to paint
                   the four painted
                   rectangles on the right




                           examples/html5/canvas/translate.html

Tuesday, February 26, 13
Scaling


                   scales the rendering context size

                   x and y are scale factors

                   translate before scale to maintain position




Tuesday, February 26, 13
Scale Example




                                   examples/html5/canvas/scale.html

Tuesday, February 26, 13
Rotation

                   Rotates a shape around its (0, 0) point of origin

                   Angle is specified in radians.
                   Math.PI     = 180 deg (half a circle)
                   Math.PI / 4 = 45 deg

                   Translate before rotate to maintain position




Tuesday, February 26, 13
Example: Rotation
         ctx.translate(75,75);

         for (var i=1;i<6;i++){
           ctx.save();
           ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)';

             for (var j=0;j<i*6;j++){ // draw individual dots
               ctx.rotate(Math.PI*2/(i*6));
               ctx.beginPath();
               ctx.arc(0,i*12.5,5,0,Math.PI*2,true);
               ctx.fill();
             }

             ctx.restore();
         }




Tuesday, February 26, 13
Example: Rotation
                   The background was
                   painted with a gradient   ctx.save();

                   fill                       var grad = ctx.createLinearGradient(0, 0,
                                             150, 0);
                                             grad.addColorStop(0, "#888");
                                             grad.addColorStop(1, "#eee");
                   Notice the save() and     ctx.fillStyle = grad;
                   restore() at the          ctx.fillRect(0, 0, 150, 150);
                                             ctx.fill();

                   beginning and end.        ctx.restore();


                   Now we can put the
                   code inside a function,
                   and it won’t affect
                   outside code

Tuesday, February 26, 13
Exercise

                   Draw the clock on the
                   right

                   Use rotate and
                   translate to simplify
                   calculations

                   Bonus: Show the time




Tuesday, February 26, 13
Image Filters




Tuesday, February 26, 13
Drawing Images on
                   Canvas
                   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



Tuesday, February 26, 13
Image Drawing API

                  drawImage(image, x, y)
                  paint an entire image object on the canvas at position (x,y)



                  drawImage(image, x, y, w, h)
                  paint an entire image object on the canvas, scaling it to size (w,h)



                  drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
                  paint a slice of the image on a canvas, can use dw,dh to scale




Tuesday, February 26, 13
Drawing Images and
                   File API
                   Use input type=”file” to upload a photo from the
                   phone’s camera or gallery

                   Access the image and paint it on a canvas using
                   HTML5 File API




Tuesday, February 26, 13
Reading The Photo
                   FileReader is used to read a photo from the input
                   field

                   reader.readAsDataURL( input_field ) - reads the
                   data

                   reader emits load event when done

                   Example: http://jsfiddle.net/influenztial/qy7h5/



Tuesday, February 26, 13
Image Filters

                      For the next few slides, we’ll create a Filters
                      object. Each filter is a function of that Filters
                      object

                      The Filters object is responsible for reading pixel
                      data and interacting with the canvas

                      A filter function takes pixel data and
                      manipulates it


Tuesday, February 26, 13
Filters Code

                      When testing on
                      desktop, some                       canvas.toDataURL()
                      browsers will throw                 ctx.getImageData(sx, sy, sw, sh)
                      security exceptions if              ctx.putImageData(data, dx, dy)
                      the page is read locally.

                      Code:
                      examples/html5/canvas/filters.html




Tuesday, February 26, 13
Canvas Exercise
                   Implement a mobile drawing app using the canvas
                   and touch events

                   App should have a footer with a selection of
                   colors. Tapping a color sets current color

                   Tapping anywhere on screen should draw in the
                   selected color

                   Bonus: share photo on server



Tuesday, February 26, 13
HTML5 Drag & Drop




Tuesday, February 26, 13
HTML5 Drag & Drop


                   Started back in IE5

                   Still wrong




Tuesday, February 26, 13
Check Support

                if (Modernizr.draganddrop) {
                  // Browser supports HTML5 DnD.
                } else {
                  // Fallback to a library solution.
                }




Tuesday, February 26, 13
Draggable Content
       <div id="columns">
         <div class="column" draggable="true"><header>A</header></div>
         <div class="column" draggable="true"><header>B</header></div>
         <div class="column" draggable="true"><header>C</header></div>
       </div>


        Selections, img and anchors with href are draggable
        by default




Tuesday, February 26, 13
Some CSS Extras

             [draggable] {
               -moz-user-select: none;
               -khtml-user-select: none;
               -webkit-user-select: none;
               user-select: none;
               cursor: move;
             }




Tuesday, February 26, 13
And The Fun Part

                   7 Dragging Events:

                           dragstart, drag,

                           dragenter, dragleave, dragover

                           drop

                           dragend



Tuesday, February 26, 13
For drop events:

        cancel defaults for

        dragover and dragenter


Tuesday, February 26, 13
Demo1: Dropzone


                   Prevent default from bad events

                   Handle good event

                   http://jsbin.com/oberec/1/edit




Tuesday, February 26, 13
Alerting Drop Zone

                   Use dragenter and dragleave to alert user they’re
                   in the drop zone

                   Demo:
                   http://jsbin.com/oberec/4/edit




Tuesday, February 26, 13
Transferring Data

     function handleDragStart(e) {
       e.dataTransfer.setData('text/html', this.innerHTML);
     }


      function handleDrop(e) {
        e.stopPropagation();  
        this.innerHTML = e.dataTransfer.getData('text/html');
       
        return false;
      }




Tuesday, February 26, 13
Other dataTransfer
                   Use e.dataTransfer.files to get data dragged from
                   desktop

              function handleDrop(e) {
                e.stopPropagation();
                e.preventDefault();
               
                var files = e.dataTransfer.files;
                for (var i = 0, f; f = files[i]; i++) {
                  // Read the File objects in this FileList.
                }
              }




Tuesday, February 26, 13
Other dataTransfer
                   Use setData to allow dragging “out of” the
                   browser

             var file = document.getElementById("dragout");
              
             file.addEventListener("dragstart",function(evt){
                 evt.dataTransfer.setData("DownloadURL",fileDetails);
             },false);




Tuesday, February 26, 13
Q&A
Tuesday, February 26, 13
Thank You

                   Slides By:

                           Ynon Perek

                           ynon@ynonperek.com

                           ynonperek.com




Tuesday, February 26, 13

Más contenido relacionado

Destacado

Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIYnon Perek
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer ToolboxYnon Perek
 
HTML5 and the Open Web Platform
HTML5 and the Open Web PlatformHTML5 and the Open Web Platform
HTML5 and the Open Web PlatformBeat Signer
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScriptYnon Perek
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScriptYnon Perek
 
02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript SyntaxYnon Perek
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 
Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming IntroYnon Perek
 

Destacado (14)

Css2
Css2Css2
Css2
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
Frontend Engineer Toolbox
Frontend Engineer ToolboxFrontend Engineer Toolbox
Frontend Engineer Toolbox
 
08 ajax
08 ajax08 ajax
08 ajax
 
Backbone
BackboneBackbone
Backbone
 
HTML5 and the Open Web Platform
HTML5 and the Open Web PlatformHTML5 and the Open Web Platform
HTML5 and the Open Web Platform
 
Intro to SVGs
Intro to SVGsIntro to SVGs
Intro to SVGs
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
 
03 Advanced JavaScript
03 Advanced JavaScript03 Advanced JavaScript
03 Advanced JavaScript
 
Performance
PerformancePerformance
Performance
 
02 JavaScript Syntax
02 JavaScript Syntax02 JavaScript Syntax
02 JavaScript Syntax
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
Web Programming Intro
Web Programming IntroWeb Programming Intro
Web Programming Intro
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 

Similar a Html5 apis

Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsArtur Cistov
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Artur Cistov
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application FrameworkRan Mizrahi
 
Intro to Backbone.js by Azat Mardanov for General Assembly
Intro to Backbone.js by Azat Mardanov for General AssemblyIntro to Backbone.js by Azat Mardanov for General Assembly
Intro to Backbone.js by Azat Mardanov for General AssemblyAzat Mardanov
 
PHP Performance tuning for Drupal 8
PHP Performance tuning for Drupal 8PHP Performance tuning for Drupal 8
PHP Performance tuning for Drupal 8Acquia
 
Kharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendKharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendMax Klymyshyn
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memoryMauro Cassani
 
Windows Azure Web Sites - Things they don’t teach kids in school - Comunity D...
Windows Azure Web Sites- Things they don’t teach kids in school - Comunity D...Windows Azure Web Sites- Things they don’t teach kids in school - Comunity D...
Windows Azure Web Sites - Things they don’t teach kids in school - Comunity D...Maarten Balliauw
 
Your browser, your storage (extended version)
Your browser, your storage (extended version)Your browser, your storage (extended version)
Your browser, your storage (extended version)Francesco Fullone
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2Niti Chotkaew
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabricMark Ginnebaugh
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performanceAbhishek Sur
 
Caching Enhancement in ASP.NET 4.0
Caching Enhancement in ASP.NET 4.0Caching Enhancement in ASP.NET 4.0
Caching Enhancement in ASP.NET 4.0Abhijit Jana
 

Similar a Html5 apis (20)

Front-end optimisation & jQuery Internals
Front-end optimisation & jQuery InternalsFront-end optimisation & jQuery Internals
Front-end optimisation & jQuery Internals
 
Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)Front-end optimisation & jQuery Internals (Pycon)
Front-end optimisation & jQuery Internals (Pycon)
 
Wix Application Framework
Wix Application FrameworkWix Application Framework
Wix Application Framework
 
2016 03 15_biological_databases_part4
2016 03 15_biological_databases_part42016 03 15_biological_databases_part4
2016 03 15_biological_databases_part4
 
your browser, your storage
your browser, your storageyour browser, your storage
your browser, your storage
 
your browser, my storage
your browser, my storageyour browser, my storage
your browser, my storage
 
WebGUI Developers Workshop
WebGUI Developers WorkshopWebGUI Developers Workshop
WebGUI Developers Workshop
 
Caching By Nyros Developer
Caching By Nyros DeveloperCaching By Nyros Developer
Caching By Nyros Developer
 
Intro to Backbone.js by Azat Mardanov for General Assembly
Intro to Backbone.js by Azat Mardanov for General AssemblyIntro to Backbone.js by Azat Mardanov for General Assembly
Intro to Backbone.js by Azat Mardanov for General Assembly
 
PHP Performance tuning for Drupal 8
PHP Performance tuning for Drupal 8PHP Performance tuning for Drupal 8
PHP Performance tuning for Drupal 8
 
Kharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backendKharkivpy#3: Javascript and Python backend
Kharkivpy#3: Javascript and Python backend
 
Caching objects-in-memory
Caching objects-in-memoryCaching objects-in-memory
Caching objects-in-memory
 
Windows Azure Web Sites - Things they don’t teach kids in school - Comunity D...
Windows Azure Web Sites- Things they don’t teach kids in school - Comunity D...Windows Azure Web Sites- Things they don’t teach kids in school - Comunity D...
Windows Azure Web Sites - Things they don’t teach kids in school - Comunity D...
 
Your browser, your storage (extended version)
Your browser, your storage (extended version)Your browser, your storage (extended version)
Your browser, your storage (extended version)
 
High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2High Performance Ajax Applications 1197671494632682 2
High Performance Ajax Applications 1197671494632682 2
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Microsoft Windows Server AppFabric
Microsoft Windows Server AppFabricMicrosoft Windows Server AppFabric
Microsoft Windows Server AppFabric
 
GlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and FutureGlassFish and JavaEE, Today and Future
GlassFish and JavaEE, Today and Future
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
 
Caching Enhancement in ASP.NET 4.0
Caching Enhancement in ASP.NET 4.0Caching Enhancement in ASP.NET 4.0
Caching Enhancement in ASP.NET 4.0
 

Más de Ynon Perek

09 performance
09 performance09 performance
09 performanceYnon Perek
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web IntroYnon Perek
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threadsYnon Perek
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile DevicesYnon Perek
 
Architecture app
Architecture appArchitecture app
Architecture appYnon Perek
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsYnon Perek
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and RubyYnon Perek
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application TestingYnon Perek
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design PatternsYnon Perek
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application SecurityYnon Perek
 

Más de Ynon Perek (20)

Regexp
RegexpRegexp
Regexp
 
Html5 intro
Html5 introHtml5 intro
Html5 intro
 
09 performance
09 performance09 performance
09 performance
 
Mobile Web Intro
Mobile Web IntroMobile Web Intro
Mobile Web Intro
 
Qt multi threads
Qt multi threadsQt multi threads
Qt multi threads
 
Vimperl
VimperlVimperl
Vimperl
 
Syllabus
SyllabusSyllabus
Syllabus
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
 
Network
NetworkNetwork
Network
 
Architecture app
Architecture appArchitecture app
Architecture app
 
Cryptography
CryptographyCryptography
Cryptography
 
Unit Testing JavaScript Applications
Unit Testing JavaScript ApplicationsUnit Testing JavaScript Applications
Unit Testing JavaScript Applications
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
Introduction to Selenium and Ruby
Introduction to Selenium and RubyIntroduction to Selenium and Ruby
Introduction to Selenium and Ruby
 
Introduction To Web Application Testing
Introduction To Web Application TestingIntroduction To Web Application Testing
Introduction To Web Application Testing
 
Accessibility
AccessibilityAccessibility
Accessibility
 
Angularjs
AngularjsAngularjs
Angularjs
 
Js memory
Js memoryJs memory
Js memory
 
Qt Design Patterns
Qt Design PatternsQt Design Patterns
Qt Design Patterns
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 

Último

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Último (20)

Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

Html5 apis

  • 2. Web Tech History 1991 HTML 1994 HTML2 1996 CSS1 + JavaScript 1997 HTML4 1998 CSS2 2000 XHTML1 2002 Tableless Web Design 2005 Ajax 2009 HTML5 Tuesday, February 26, 13
  • 3. HTML5 What Syntactical Features (audio, video) Semantical Features (section, article) New APIs Tuesday, February 26, 13
  • 4. HTML5 How Progressive Enhancements Existing web sites can move to HTML5 Old browsers will still be able to use the page Modernizr: http://www.modernizr.com/ Tuesday, February 26, 13
  • 5. HTML5 New APIs Web Storage Geolocation Web SQL Device Orientation Application Cache Form Enhancements Web Workers Audio, Video Web Socket Canvas Desktop Notifications Web GL Drag & Drop History API File System API And More... Tuesday, February 26, 13
  • 6. Modernizr: Before We Begin Script Loader Feature Detector Tuesday, February 26, 13
  • 7. Hello Modernizr Modernizr.load({   test: 3 > 5,   yep : 'http://code.jquery.com/ jquery-1.9.1.min.js',   nope: 'http://cdnjs.cloudflare.com/ ajax/libs/zepto/1.0rc1/zepto.min.js' }); Tuesday, February 26, 13
  • 8. More Loader Features Specify only “yep” or “nope” Provide array Complete callback Demo: http://jsbin.com/abowap/2/edit Tuesday, February 26, 13
  • 9. polyfill (n): a JavaScript shim that replicates the standard API for older browsers Tuesday, February 26, 13
  • 10. Feature Detection Modernizr.applicationcache Modernizr.canvas Modernizr.audio Modernizr.inputtypes Demo: http://jsbin.com/abowap/3/edit Tuesday, February 26, 13
  • 11. Feature Detection + Polyfill Modernizr.load({     test: Modernizr.input.placeholder,     nope: [             'placeholder_polyfill.min.css',             'placeholder_polyfill.jquery.min.combo.js'           ] }); Tuesday, February 26, 13
  • 13. Offline Storage Work Offline Store Persistent State Tuesday, February 26, 13
  • 14. Local Data Storage How do you store data on a client’s machine ? Tuesday, February 26, 13
  • 16. Server Client Tuesday, February 26, 13
  • 17. Local Storage Before HTML5: cookies were used to store data on the client side Cookies Disadvantages: Limited size (4k) Sent with every request Complex to use Tuesday, February 26, 13
  • 18. Local Storage A JavaScript API for storing client side data Can store up to 5MB (per site) Simple API Never run out of space Tuesday, February 26, 13
  • 19. Local Storage Store Data window.localStorage.setItem(“key”, “value”); Read Data window.localStorage.getItem(“key”); Remove Data window.localStorage.removeItem(“key”); Tuesday, February 26, 13
  • 20. Local Storage Can also use direct access on the storage object, so this code also works: window.localStorage.username = “Jimmy”; var username = window.localStorage.username; console.log(‘Hello ‘ + username); Tuesday, February 26, 13
  • 21. Local Storage Methods: clear() key(idx) length() Tuesday, February 26, 13
  • 22. Session Storage Interface is the same as localStorage Lifetime is only for the current browser window or tab (or browser session) Best used for temporary preferences that should not be shared between tabs Tuesday, February 26, 13
  • 23. Storage Lab We’ll implement an address book app Keeps a list of contacts info: name, phone number, email Provide add/view/delete contacts Tuesday, February 26, 13
  • 24. Storage Lab Use the starter: https://github.com/ynonp/advanced-fed- examples/tree/master/contacts Tuesday, February 26, 13
  • 25. Offline Web App Online-Offline Apps Sync with the Cloud, but can suffer a downtime (Think Google Gears) Can run completely offline app as a standalone Mobile - Save bandwidth Tuesday, February 26, 13
  • 26. Offline Web App GET MANIFEST CACHE MANIFEST index.html style/main.css script/main.js Tuesday, February 26, 13
  • 27. Cache Manifest File Lists all the files that should be stored for offline access Enable with: <html manifest="example.appcache"> Tuesday, February 26, 13
  • 28. example.appcache CACHE MANIFEST Required header index.html CACHE MANIFEST stylesheet.css A list of cached files images/logo.png scripts/main.js Tuesday, February 26, 13
  • 29. Demo Caching A Website Tuesday, February 26, 13
  • 30. Offline Web App The cache manifest is divided to sections, the default is called CACHE Every file listed in the default CACHE section will be cached by the browser forever (or until explicitly deleted by the user) Tuesday, February 26, 13
  • 31. Offline Web App The NETWORK section lists files that should never be cached Best used for dynamic content (think gmail) Tuesday, February 26, 13
  • 32. Offline Web App The FALLBACK section lists fallback content that should be used if network is not available So, if you’re trying to read a message while offline, you can get a nice formatted error page Tuesday, February 26, 13
  • 33. Manifest Cache Cache the file locally, CACHE never refresh Files should not be NETWORK cached Cache a fallback FALLBACK content Tuesday, February 26, 13
  • 34. Offline App Exercise A Dynamic reader with two pages First lists available articles, the second displays a given article Use your favorite server side technology and jQM Which files do you put in each manifest section ? Tuesday, February 26, 13
  • 35. Manifest - The Good Can store any file locally Provides offline/online app functionality Transparent to the user Tuesday, February 26, 13
  • 36. Manifest - The Bad Not suitable for data storage Complex update logic Tuesday, February 26, 13
  • 37. Web SQL The final storage option for offline apps is the Web SQL Allows using a local database to better store relational data Best suited for hierarchical lists apps Tuesday, February 26, 13
  • 38. Q&A Storage Geo Location Video Canvas Tuesday, February 26, 13
  • 39. Geo Location Detect where your user is now Show nearby places Display location aware data Tuesday, February 26, 13
  • 40. Technologies GPS A-GPS Cell Information WiFi Positioning Tuesday, February 26, 13
  • 41. GPS Global Positioning System Accuracy error: 2-10m Requires clear sky view Time to position: 5 seconds - 5 minutes Tuesday, February 26, 13
  • 42. A-GPS Uses both GPS chip and network information to get location Much faster to get location Tuesday, February 26, 13
  • 43. Cell Information Uses cell towers to calculate a device’s location Accuracy: A block or up to some km Time to location: immediate Tuesday, February 26, 13
  • 44. WiFi Positioning Detect location using a list of wireless routers in your area Relies on existing router databases Tuesday, February 26, 13
  • 45. Location API Supported Platforms: iPhone 3.0+ Android 2.0+ Tuesday, February 26, 13
  • 46. Location API function get_location() {   navigator.geolocation.getCurrentPosition(show_map); } function show_map(position) {   var lat = position.coords.latitude;   var long = position.coords.longitude;   var when = position.timestamp;   // show me the map } Tuesday, February 26, 13
  • 47. Location API navigator.geolocation is the entry point for all location related calls Location querying is async, so a callback is supplied User will be asked permission to share location Tuesday, February 26, 13
  • 48. Location API iPhone browser asks user permissions before sharing location Tuesday, February 26, 13
  • 49. Location API Location API uses callbacks to perform error handling When working with location, always consider errors Tuesday, February 26, 13
  • 50. Location API getCurrentPosition( successCallback, optional errorCallback, optional config ); Tuesday, February 26, 13
  • 51. The Coord object coords.latitude coords.longitude coords.altitude coords.accuracy coords.altitudeAccuracy coords.heading coords.speed timestamp Tuesday, February 26, 13
  • 52. The Coord Object Not all fields will be available at all times Sizes are specified in meters and degrees timestamp is a DOMTimestamp (acts like a Date object) Tuesday, February 26, 13
  • 53. Location Config last parameter to getCurrentPosition is a config object there are 3 configuration options available: timeout maximumAge enableHighAccuracy Tuesday, February 26, 13
  • 54. Using Config window.navigator.geolocation.getCurrentPosition( successCallback, failureCallback, How long to wait before giving up { timeout : 0, (in ms) maximumAge : 60000, Try to use a cached value aged (in ms) enableHighAccuracy : false }); Use the most accurate positioning method Tuesday, February 26, 13
  • 55. Handle Errors The errorCallback takes a single argument called error object The object has two fields: error.code & error.message Use error.message for debug only Tuesday, February 26, 13
  • 56. Next: The Map Tuesday, February 26, 13
  • 57. Show The Map On the iPhone, a redirect to a google maps url starts the map application The Good: easy to use The Bad: user leaves the app Tuesday, February 26, 13
  • 58. Google Maps API A JS API to display embedded maps in web sites Works on both desktop and mobile devices (Almost) Free to use Tuesday, February 26, 13
  • 59. Google Maps API 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 Place markers on the map using google.maps.Marker Full documentation: http://developer.google.com/apis/maps/ documentation/javascript/ Tuesday, February 26, 13
  • 60. Google Maps API Maps Workflow: Choose a div Create a new google.maps.Map(...) Remember to set minimum height on the div Tuesday, February 26, 13
  • 61. Objects To Note google.maps.LatLng - represents a latitude/ longitude pair Methods: lat() returns the lat value lng() returns the long value Tuesday, February 26, 13
  • 62. Objects To Note google.maps.Map( element, options ) Interesting Methods: panBy( x, y ) - move the map by x,y panTo( latlng ) - move the map to latlng setZoom( zoom ) Tuesday, February 26, 13
  • 63. Objects To Note google.maps.MapOptions: configuration object Interesting options center: latlng disableDefaultUI: boolean draggable: boolean mapTypeId: HYBRID, ROADMAP, SATELLITE Tuesday, February 26, 13
  • 64. Demo Show Location On Map Tuesday, February 26, 13
  • 65. Location Tracking Receive notifications about location changes Can use for navigation apps, sport apps, and more Browser must remain open Tuesday, February 26, 13
  • 66. Location Tracking use 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 Tuesday, February 26, 13
  • 67. Exercise: Where’s My Car Write a parking reminder app One button titled “parked” which marks current location and keeps it in local storage Another button titled “find” which shows a map leading to your car Keep data in local storage Tuesday, February 26, 13
  • 68. Q&A Storage Geo Location (iPhone, Android) Video & Audio (iPhone, Android) Canvas (iPhone, Android) Tuesday, February 26, 13
  • 69. VIDEO THE EASY WAY Tuesday, February 26, 13
  • 70. Video Tag HTML5 introduces a <video> tag to embed videos in a web page. Different browsers support different video formats. The <video> tag can specify multiple formats. Tuesday, February 26, 13
  • 71. Video Formats Video formats are like languages The same video can be encoded in different formats A browser must “speak the language” to be able to play the video Tuesday, February 26, 13
  • 72. Video Converter Miro is a free open source video player and converter http:// www.getmiro.com Tuesday, February 26, 13
  • 73. Browser Support HTML5 spec does not define a video codec to use h.264 is the most widely supported. Plays on iPhone and Android Tuesday, February 26, 13
  • 74. The Markup Poster image file name <video poster=”star.png”> <source src=”zebra.mp4” /> Video file name. Usually mp4 </video> for mobile devices Tuesday, February 26, 13
  • 75. Limitations Video will start playing in a dedicated “player” window, when the user taps it It is not possible to auto play the video on mobile It is not possible to embed other content on the video on mobile Tuesday, February 26, 13
  • 76. Audio Tag Structured like a Video tag iPhone and Android support MP3 No autoplay Tuesday, February 26, 13
  • 77. Lab Audio SoundBoard Use Animal Sounds: http://apps.ynonperek.com/ audio.zip Images: http:// apps.ynonperek.com/images.zip Use starter: https://github.com/ynonp/ mobileweb-examples/blob/ master/html5/SoundBoard/ audioboard_starter.html Tuesday, February 26, 13
  • 78. Q&A Storage Geo Location Video & Audio Canvas (iPhone, Android) Tuesday, February 26, 13
  • 80. HTML5 Canvas A 2d graphics canvas for HTML apps Games Dynamic images Client-side painting (saves bandwidth) Tuesday, February 26, 13
  • 81. Hello Canvas An HTML element <canvas> on the markup JS code to do actual painting Tuesday, February 26, 13
  • 82. Hello Canvas The canvas element has no content and no border of its own A canvas keeps a painting context on which we perform the drawing First example uses context.fillText() examples/canvas/intro.html Tuesday, February 26, 13
  • 83. Basic Drawing Context object provides the drawing functions. Each takes coordinates and data. Drawing style is determined by setting attributes on the context object. Most style properties are plain text strings Tuesday, February 26, 13
  • 85. Drawing Rectangles Let’s start with drawing rectangles fillRect(x, y, w, h) note fillRect draws a strokeRect(x, y, w, h) filled rectangle, while clearRect(x, y, w, h) strokeRect draws just the outline fillStyle and strokeStyle determine the colors Tuesday, February 26, 13
  • 87. Drawing Paths A composite shape on the canvas is called “path” Paths are made of lines, arcs, curves and rectangles A path can be filled or stoked. Nothing is painted until either fill() or stroke() is called Tuesday, February 26, 13
  • 88. Drawing Paths moveTo(x, y) Lines are painted with lineTo and moveTo lineTo(x, y) stroke() performs the actual drawing Tuesday, February 26, 13
  • 89. Lines Example ctx.beginPath(); ctx.strokeStyle = "hsl(249, 41%, 50%)"; ctx.lineWidth = 6; ctx.moveTo(0, 0); ctx.lineTo(20, 10); ctx.lineTo(0, 20); ctx.stroke(); Cool Color Selector: http://mothereffinghsl.com/ Tuesday, February 26, 13
  • 90. Using The Image It’s possible to use an image drawn in a canvas for other elements get the image url using: canvas.toDataURL() use image url as a source attribute of an img tag Extra: draw on a hidden canvas Tuesday, February 26, 13
  • 91. Drawing Circles use arc() and arcTo() to arc(x, y, radius, draw circles or parts of startAngle, them endAngle, antiClockWise) Degrees are specified in radians. arcTo(x1, y1, Math.PI = 180 deg x2, y2, radius) remember to fill() or stroke() Tuesday, February 26, 13
  • 92. Exercise 1 Draw the image on the right Use moveTo and arc Bonus: add colors Tuesday, February 26, 13
  • 93. Exercise 2 Draw the image on the right Place pins randomly across the screen Tuesday, February 26, 13
  • 94. Advanced Canvas Transformations Image Filters Tuesday, February 26, 13
  • 95. Transformations supported translate(x, y) transformations: translation, scaling, rotate(angle) rotation scale(x, y) Transformations affect all drawing code performed after them Tuesday, February 26, 13
  • 96. Translation Move the origin of the canvas to another point on the canvas The new point is now (0, 0) This can make drawing code simpler Tuesday, February 26, 13
  • 97. Translation Example Use translation to paint the four painted rectangles on the right examples/html5/canvas/translate.html Tuesday, February 26, 13
  • 98. Scaling scales the rendering context size x and y are scale factors translate before scale to maintain position Tuesday, February 26, 13
  • 99. Scale Example examples/html5/canvas/scale.html Tuesday, February 26, 13
  • 100. Rotation Rotates a shape around its (0, 0) point of origin Angle is specified in radians. Math.PI = 180 deg (half a circle) Math.PI / 4 = 45 deg Translate before rotate to maintain position Tuesday, February 26, 13
  • 101. Example: Rotation ctx.translate(75,75); for (var i=1;i<6;i++){ ctx.save(); ctx.fillStyle = 'rgb('+(51*i)+','+(255-51*i)+',255)'; for (var j=0;j<i*6;j++){ // draw individual dots ctx.rotate(Math.PI*2/(i*6)); ctx.beginPath(); ctx.arc(0,i*12.5,5,0,Math.PI*2,true); ctx.fill(); } ctx.restore(); } Tuesday, February 26, 13
  • 102. Example: Rotation The background was painted with a gradient ctx.save(); fill var grad = ctx.createLinearGradient(0, 0, 150, 0); grad.addColorStop(0, "#888"); grad.addColorStop(1, "#eee"); Notice the save() and ctx.fillStyle = grad; restore() at the ctx.fillRect(0, 0, 150, 150); ctx.fill(); beginning and end. ctx.restore(); Now we can put the code inside a function, and it won’t affect outside code Tuesday, February 26, 13
  • 103. Exercise Draw the clock on the right Use rotate and translate to simplify calculations Bonus: Show the time Tuesday, February 26, 13
  • 105. Drawing Images on Canvas 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 Tuesday, February 26, 13
  • 106. Image Drawing API drawImage(image, x, y) paint an entire image object on the canvas at position (x,y) drawImage(image, x, y, w, h) paint an entire image object on the canvas, scaling it to size (w,h) drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) paint a slice of the image on a canvas, can use dw,dh to scale Tuesday, February 26, 13
  • 107. Drawing Images and File API Use input type=”file” to upload a photo from the phone’s camera or gallery Access the image and paint it on a canvas using HTML5 File API Tuesday, February 26, 13
  • 108. Reading The Photo FileReader is used to read a photo from the input field reader.readAsDataURL( input_field ) - reads the data reader emits load event when done Example: http://jsfiddle.net/influenztial/qy7h5/ Tuesday, February 26, 13
  • 109. Image Filters For the next few slides, we’ll create a Filters object. Each filter is a function of that Filters object The Filters object is responsible for reading pixel data and interacting with the canvas A filter function takes pixel data and manipulates it Tuesday, February 26, 13
  • 110. Filters Code When testing on desktop, some canvas.toDataURL() browsers will throw ctx.getImageData(sx, sy, sw, sh) security exceptions if ctx.putImageData(data, dx, dy) the page is read locally. Code: examples/html5/canvas/filters.html Tuesday, February 26, 13
  • 111. Canvas Exercise Implement a mobile drawing app using the canvas and touch events App should have a footer with a selection of colors. Tapping a color sets current color Tapping anywhere on screen should draw in the selected color Bonus: share photo on server Tuesday, February 26, 13
  • 112. HTML5 Drag & Drop Tuesday, February 26, 13
  • 113. HTML5 Drag & Drop Started back in IE5 Still wrong Tuesday, February 26, 13
  • 114. Check Support if (Modernizr.draganddrop) {   // Browser supports HTML5 DnD. } else {   // Fallback to a library solution. } Tuesday, February 26, 13
  • 115. Draggable Content <div id="columns">   <div class="column" draggable="true"><header>A</header></div>   <div class="column" draggable="true"><header>B</header></div>   <div class="column" draggable="true"><header>C</header></div> </div> Selections, img and anchors with href are draggable by default Tuesday, February 26, 13
  • 116. Some CSS Extras [draggable] {   -moz-user-select: none;   -khtml-user-select: none;   -webkit-user-select: none;   user-select: none;   cursor: move; } Tuesday, February 26, 13
  • 117. And The Fun Part 7 Dragging Events: dragstart, drag, dragenter, dragleave, dragover drop dragend Tuesday, February 26, 13
  • 118. For drop events: cancel defaults for dragover and dragenter Tuesday, February 26, 13
  • 119. Demo1: Dropzone Prevent default from bad events Handle good event http://jsbin.com/oberec/1/edit Tuesday, February 26, 13
  • 120. Alerting Drop Zone Use dragenter and dragleave to alert user they’re in the drop zone Demo: http://jsbin.com/oberec/4/edit Tuesday, February 26, 13
  • 121. Transferring Data function handleDragStart(e) {   e.dataTransfer.setData('text/html', this.innerHTML); } function handleDrop(e) {   e.stopPropagation();     this.innerHTML = e.dataTransfer.getData('text/html');     return false; } Tuesday, February 26, 13
  • 122. Other dataTransfer Use e.dataTransfer.files to get data dragged from desktop function handleDrop(e) {   e.stopPropagation();   e.preventDefault();     var files = e.dataTransfer.files;   for (var i = 0, f; f = files[i]; i++) {     // Read the File objects in this FileList.   } } Tuesday, February 26, 13
  • 123. Other dataTransfer Use setData to allow dragging “out of” the browser var file = document.getElementById("dragout");   file.addEventListener("dragstart",function(evt){     evt.dataTransfer.setData("DownloadURL",fileDetails); },false); Tuesday, February 26, 13
  • 125. Thank You Slides By: Ynon Perek ynon@ynonperek.com ynonperek.com Tuesday, February 26, 13