Table of Contents

Help

Left Arrow - Previous Slide

Right Arrow - Next Slide

Up Arrow - First Slide

Down Arrow - Last Slide

Topic
  • What's new in HTML 5?

    • What's new in HTML?

    • What's new in CSS 3?

    • What's new in APIs?

  • Issues with HTML 5

  • How to decide which feature to go with?

What's new in HTML5?

We will cover

  • HTML Tags

  • CSS3

  • APIs

New Features in HTML

We will cover

  • New DocType & Syntax

  • New Tags: Article, Section, Nav, etc.

  • Audio/Video Tag

  • Canvas & SVG

  • New Form Elements

New DocType & Syntax

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript">
var data = "abc"
</script>
<link type="text/css" rel="stylesheet" href="css/app.css" media="screen">
<title>HTML4</title>
</head>
<body>
<h1>HTML 4</h1>
<p>View Source</p>
</body>
</html>


<!DOCTYPE HTML>
<html lang="en">
<head>
<meta content="text/html;charset=utf-8">
<script src="js/app.js"></script>
<script>
var data = "abc"
</script>
<link rel="stylesheet" href="css/app.css" media="screen">
<title>HTML5</title>
</head>
<body>
<h1>HTML 5</h1>
<p>View Source</p>
</body>
</html>

New Tags: Article, Section, Nav, etc
Div Hell

Traditional Approach

Imagine everything element in your HTML Page to be div and then try to figure out which element ends where. Also think from the point of view of a code which is looking at the DIVs, there would be no way to find out if a given div indicates a header section, a actual content section, a navigation area etc.

Live Demo - See Example

<div>
    <div>
        ...
    </div>
    <div>
        <div>
        ...
        </div>
    </div>
</div>
        
Article, Section, Nav, Aside tags

HTML 5 Tags Approach

Specific Tags for Specific Purpose - See Example

Now Imagine different tags available like Article, Section, Nav, Header, Footer. The best part of about all these tags is that these are nothing but DIVs but with different name

Live Demo - See Example

<section>
    <article>
        <header>
            ....
        <header>
        ...
    </article>
    <aside>
        <nav>
        ...
        </nav>
    </aside>
</section>
        
Audio & Video Tags
Video Tag Demo
Video Tag - Source Code
<video width="640" height="368" id="myVideo" controls>
    <source src="http://www.html5videoplayer.net/videos/madagascar3.ogv"
        type='video/ogg;codecs="theora, vorbis"'>
    <source src="http://www.html5videoplayer.net/videos/madagascar3.mp4"
        type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
    <source src="http://www.html5videoplayer.net/videos/madagascar3.webm"
        type='video/webm; codecs="vp8.0, vorbis"'>
</video>
var videoElem = document.getElementById("myVideo");

//Play Video
videoElem.play();

//Pause Video
videoElem.pause();

//Forward Rewind
videoElem.currentTime = 100;
Canvas & SVG
Canvas Demo

Demo

Source Code

var canvasElem = document.getElementById("canvas1");

var ctx = canvasElem.getContext('2d');
ctx.fillStyle = "#00A308";
ctx.beginPath();
ctx.arc(220, 220, 50, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

ctx.fillStyle = "#FF1C0A";
ctx.beginPath();
ctx.arc(100, 100, 100, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

//the rectangle is half transparent
ctx.fillStyle = "rgba(255, 255, 0, .5)";
ctx.beginPath();
ctx.rect(15, 150, 120, 120);
ctx.closePath();
ctx.fill();
        
Drawing Capabilities
  • Drawing APIs
    • lineTo(),moveTo(),arcTo()
  • Transformation APIs
    • scale(), translate(), transform()
  • Context APIs
    • save()
    • restore()
Drawing Concept

Answer following Questions

  • At 115 Degree rotation what is x,y?
  • At 115 Degree rotation & 1/s scale what is x,y?

Canvas Drawing

Code Snippet - 1

Code

ctx.save();
ctx.rect(0,20,80,40);
ctx.fill();
ctx.fillText("0,20",0,10);
ctx.restore();

ctx.save();
ctx.translate(40,60);
ctx.rect(0,20,80,40);
ctx.fill();
ctx.fillText("40,80",0,10);
ctx.restore();

        

Canvas Drawing

Code Snippet - 2

Code

ctx.save();
ctx.translate(140,100);
ctx.rotate(170);
ctx.rect(0,20,80,40);
ctx.fill();
ctx.fillText("@ 115 Degree what is x,y",0,10);
ctx.restore();

ctx.save();
ctx.translate(40,200);
ctx.rotate(170);
ctx.scale(0.5,0.5);
ctx.rect(0,20,80,40);
ctx.fill();
ctx.fillText("@ 115 Deg & 1/2 scale what is x,y",0,0);
ctx.restore();
        

Canvas Drawing

Canvas Game

Game Concept

<script>
setInterval(gameLoop,100); function gameLoop(){ manipulateModel(); clearCanvas(); drawModel(); } <script/>

Canvas Drawing

SVG Demo
Hello World Text grouped with shapes
SVG - Code
<style>
    circle.myGreen {
        stroke: #006600;
        fill: #00cc00;
    }
    circle.myRed {
        stroke: #660000;
        fill: #cc0000;
    }
</style>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <rect x="10" y="10" height="100" width="100" style="stroke:#ff0000; fill: #0000ff"</rect>
    <rect x="50" y="50" height="110" width="110" style="stroke:#ff0000; fill: #ccccff" transform="translate(30) rotate(45 50 50)"></rect>
    <text x="70" y="100" transform="translate(30) rotate(45 50 50)">Hello World</text>
    <circle class="myGreen" cx="140" cy="40" r="24"/>
    <circle class="myRed" cx="140" cy="100" r="24"/>

    <g transform="rotate(300 300 50)">
        <line x1="310" y1="310" x2="385" y2="310" style="stroke: #006600;"/>
        <rect x="310" y="320" height="50" width="75" style="stroke: #006600; fill: #006600"/>
        <text x="310" y="390" style="stroke: #660000; fill: #660000">
            Text grouped with shapes
        </text>
    </g>
</svg>
New Form Element
<input type="text" required=""/>
<input type="email" value="some@email.com"/>
<input type="date" min="2010-08-14" max="2011-08-14" value="2010-08-14"/>
<input type="range" min="0" max="50" value="10"/>
<input type="tel" placeholder="(555) 555-5555" pattern="^\(?\d{3}\)?[-\s]\d{3}[-\s]\d{4}.*?$"/>
<input type="color" placeholder="e.g. #bbbbbb"/>
<input type="number" step="1" min="-5" max="10" value="0"/>
<input results="10" type="search" placeholder="Search..."/>
CSS3
  • What's new in CSS3 ?

    • New Properties

    • Transforms

    • Transitions

    • Animation

Border Properties

Example

CSS Code

Simple Round
.simpleround{
    -webkit-border-radius: 50px;
    -moz-border-radius: 50px;
}
Alternate Round
.alternateround{
    -webkit-border-top-left-radius: 50px;
    -webkit-border-bottom-right-radius: 50px;
    -moz-border-radius-topleft: 50px;
    -moz-border-radius-bottomright: 50px;
}
Different Round
.differentround{
    -webkit-border-radius: 5px 200px 30px 50px;
    -moz-border-radius: 5px 200px 30px 50px;
}
Border Properties

Example

CSS Code

Ecliptical Round
.ecliptical{
    -webkit-border-radius: 100px / 30px;
    -moz-border-radius: 100px / 30px;
}
Circle
.circle{
    -webkit-border-radius: 300px;
    -moz-border-radius: 300px;
    width:50px;
    height:50px;
}
Shadow Properties

Example

CSS Code

Solid Shadow
.solidshadow{
    -webkit-box-shadow: 10px 10px #000;
    -moz-box-shadow: 10px 10px #000;
}
Blurr Shadow
.blurshadow{
    -webkit-box-shadow: 10px 10px 20px #000;
    -moz-box-shadow: 10px 10px 20px #000;
}
Blurr Shadow using rgba
.blurrrgbashadow{
    -webkit-box-shadow: 10px 10px 20px rgba(200,0,0,0.8);
    -moz-box-shadow: 10px 10px 20px rgba(200,0,0,0.8);
}
Shadow Properties

Example

CSS Code

Two Shadows
.twoshadow{
    -webkit-box-shadow: 10px 10px 20px rgba(200,0,0,0.5),
    -10px -10px 20px rgba(0,0,200,0.5);
    -moz-box-shadow: 10px 10px 20px rgba(200,0,0,0.5),
    -10px -10px 20px rgba(0,0,2000,0.5);
}
Inner Shadow
.innershadow{
    -webkit-box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
    -moz-box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}
Gradient Properties

Example

CSS Code

Linear Gradient
.lineargradienthorz{
    background-image: -webkit-gradient(linear, 0% 50%, 100% 50%, from(#0099ff), to(#000));
    background-image: -moz-linear-gradient(0% 100% 0deg, #0099ff, #000);
}
Linear Gradient at angle
.lineargradientangle{
    background-image: -webkit-gradient(linear, left top, right bottom, from(#0099ff), to(#000));
    background-image: -moz-linear-gradient(left top 315deg, #0099ff, #000);
}
Gradient Properties

Example

CSS Code

Radial Gradient
.radialgradient1{
    background-image: -webkit-gradient(radial, center center, 0, center center, 200,
    from(#0099FF), to(#000));
    background-image: -moz-radial-gradient(center, circle closest-corner, #0099FF 0%, #000
    100%);
}
Radial Gradient center
.radialgradient2{
    background-image: -webkit-gradient(radial, center center, 0, 150 150, 200, from(#0099FF),
    to(#000));

}
Text Properties

Example

CSS Code

Text Shadow

.textShadow{
    text-shadow: 15px 15px 5px black;
}

Text Inline Shadow

.textInShadow {
    color: #CCC;
    text-shadow: 0px -1px 1px #000;
}

Text Stroke

.textStroke {
    color: #FFF;
    text-shadow:-1px -1px 0 #CCC,  1px -1px 0 #CCC,
                -2px 2px 0 #555,   2px 2px 0 #555;
}
Text Properties

Example

CSS Code

Text Reflection

.textreflection{
    -webkit-box-reflect: below -10px -webkit-gradient(
    linear,
    left top, left bottom,
    from(transparent),
    color-stop(0.2, transparent),
    to(rgba(255,255,255,0.5))
    );
}

Web Fonts

@font-face {
    font-family: 'Junction';
    src: url(Junction.otf);
}

.webfont {
    font-family: 'Junction';
}
CSS Transforms
Skew
Scale X
Scale Y
Rotate X
Rotate Y
Rotate Z
Translate X
Translate Y
-webkit-transform : skew(0deg)
scale(1,1)
rotateX(0deg)
rotateY(0deg)
rotateZ(0deg)
translate(0px,0px)
This is a div, which will be modified using CSS 3 Transforms (2D & 3D)
CSS Transitions

Click on the DIVs below. Observe first div, has immediate effect and second one takes certain time. This is due to transition CSS Property

This is Div without any CSS Transitions
This is Div with CSS Transition property

transition: all 1s ease-in-out;

#with-transition{
    -webkit-transition: all 1s ease-in-out;
    -moz-transition: all 1s ease-in-out;
    -o-transition: all 1s ease-in-out;
    transition: all 1s ease-in-out;
}
Visit http://css3.bradshawenterprises.com/transitions/ for more examples.
CSS Animations
Box with Animation Effect
@-webkit-keyframes resize {
          0% {
            padding: 0;
          }
          50% {
            padding: 0 20px;
            color:white;
            -webkit-transform:translate(100px,0px)
                              rotateZ(180Deg);
            background-color:rgba(255,0,0,0.2);
          }
          100% {
            padding: 0 100px;
            background-color:rgba(255,0,0,0.9);
          }
        }

#box {
    -webkit-animation-name: resize;
    -webkit-animation-duration: 2s;
    -webkit-animation-iteration-count: infinite;
}
        
CSS Advanced Demos

Rotating Divs

1
2
3
4
APIs
  • Cors

  • Server Sent Events

  • Web Sockets

  • Web Workers

  • Storage

  • Offline Access

  • Geo & Device Sensors

  • File System and Drag and Drop

Cors

We will cover

  • Single Origin Policy

  • Proxy Work around

  • JSONP Work around

  • CORS to rescue

Traditional Ajax Demo

Traditional Ajax Request

Cors Ajax Demo

Cors Ajax Request

How did Ajax Request work this time?

Because this time server send special headers with HTTP Response, shown below

Access-Control-Allow-Headers:X-Requested-With
Access-Control-Allow-Origin:*
        
SSE - Concept

Server Sent Events Concept

  1. Polling the Server
  2. Comet/Hanging GET/Reverse Ajax
  3. Server Sent Events
SSE - Flow

Flow

  1. Client Send HTTP Request with MimeType - event-stream
  2. Server Caches the Connection and write the header -'content-type': 'text/event-stream'
  3. Server now keeps putting information on the Connection
  4. If Connection breaks, Client reconnects

Read the Blog for more details - http://html5doctor.com/server-sent-events/

SSE Protocol

Data sent by Server

//Simple Message
data: this is a simple message

//Multi line JSON Message
data: {
data:    "name":"Rohit Ghatol",
data:    "city":"Pune"
data: }

//Messages with ID
id: 33
data: this is line one
data: this is line two

//Messages with <<Custom Event>>
id: 36
event: price
data: 103.34
        
SSE Code

Code Snippets

var source = new EventSource('http://xyz.com/events');
//Callback called when connection is established
source.onopen = function () {
    connectionOpen(true);
};

//Callback called when connection issues occurs
source.onerror = function () {
    connectionOpen(false);
};

//Callback called when server sends a data
source.onmessage = function (event) {
    console.log("Server sent "+event.data);
};

source.addEventListener('<<custom event>>', function(event){
    console.log("Got Data "+event.data+" for <<custom event>>");
}, false);


        
Web Sockets - Code

Code Snippet

//Open Web Socket Connection
var socket = new WebSocket('ws://localhost:5000/echo');

//Callback for successful Connection
socket.onopen = function(event) {
  console.log("WebSocket connected Successfully");
};

//Send Message to Server
socket.send('Hello, WebSocket');

//Callback for receiving message sent by the Server
socket.onmessage = function(event) {
    console.log("Got message from server "+event.data);
}

//Callback when WebSocket Connection is terminated
socket.onclose = function(event) {
    console.log("WebSocket connection is terminated");
}
        
Web Workers
Enter Fibocanni Number at Index
Fibocanni Number is
Web Workers - Code

Main JS

var worker = new Worker('worker.js');
button.addEventListener("click",
function(){
    outputElem.innerHTML = "Calculating....";
    var index = indexElem.value;
    worker.postMessage(index);
});
worker.addEventListener('message',
function(e){
    outputElem.innerHTML=e.data;
});

Worker JS

//Web Worker
importScripts('fibonacci.js');
addEventListener('message', function(e){
  var index = parseInt(e.data);
  var result = fibonacci(index);
  postMessage(result);
})
Storage

Methods

  1. Local Storage - Persistent Key Value Pair
  2. Session Storage - Temporary Key Value Pair
  3. Web SQL - SQL Based Storage (deprecated)
  4. IndexDB - ObjectStore
Local Storage Vs Session Storage

Local Storage

  1. Key Value Store
  2. Data is persisted even after browser is closed
  3. Ideal for storing User Preferences
localStorage.preferredCountry="India";
localStorage["preferredCountry"]="India";
console.log("Preferred Country for User is "+localStorage.preferredCountry);
        

Session Storage

  1. Key Value Store
  2. Data is lost after browser is closed
  3. Ideal for storing session data
sessionStorage.lastPage=10;
sessionStorage["lastPage"]=10;
console.log("Last Page User was on is "+sessionStorage.lastPage);
        
IndexDB

Index DB Demo









    Code derived from HTML5 Rocks

    IndexDB - Open DB

    Opening IndexDB

    // Open an IndexDB Database
    var openDBRequest = indexedDB.open("dbname");
    
    openDBRequest.onsuccess = function(e) {
        //Let's store the db in global window
        window.mydb = e.result.target;
    }
    openDBRequest.onerror = function(e){
        console.log("Unable to open IndexDB "+e);
    }
            
    IndexDB - ObjectStore

    Creating an Object Store in IndexDB

    // Step 1 : Set a Version to the DB
    var setVersionRequest = indexedDB.db.setVersion(1);
    
    
    // onsuccess is the only place we can create Object Stores
    setVersionRequest.onsuccess = function(e) {
        // Step 2 : Create Store if not already created
        var store = db.createObjectStore("todo",{keyPath: "timeStamp"});
    };
    
    setVersionRequest.onerror = function(e){
        console.log("Got Error while setting DB Version "+e);
    }
    
    
    IndexDB - Add Record

    Putting Record in Object Store in IndexDB

    //Access window.mydb
    var trans = mydb.transaction(["todo"], "readwrite");
    var store = trans.objectStore("todo");
    
    var data = {
        "text": todoText,
        "timeStamp": new Date().getTime()
    };
    
    var putRequest = store.put(data);
    
    putRequest.onsuccess = function(e) {
        console.log("Record added successfully");
    };
    
    putRequest.onerror = function(e) {
        console.log("Error Adding: ", e);
    };
    
    
    IndexDB - Delete Record

    Deleting Record from Object Store in IndexDB

    //Access window.mydb
    var trans = mydb.transaction(["todo"], "readwrite");
    var store = trans.objectStore("todo");
    
    
    var deletRequest = store.delete(id);
    
    deletRequest.onsuccess = function(e) {
        console.log("Record deleted successfully");
    };
    
    deletRequest.onerror = function(e) {
        console.log("Error Deleting: ", e);
    };
    
    
    IndexDB - Retreiving Records

    Retrieving Record from Object Store in IndexDB

    //Access mydb
    var trans = mydb.transaction(["todo"], "readwrite");
    var store = trans.objectStore("todo");
    
    // Get everything in the store;
    var cursorRequest = store.openCursor();
    
    cursorRequest.onsuccess = function(e) {
        var result = e.target.result;
        if(!!result == false){
            return;
        }
    
        console.log("Retrieved Row data ="+result.value);
        result.continue();
    };
    
    cursorRequest.onerror = function(e) {
        console.log("Error Retrieving: ", e);
    };
    
    Offline Access

    Rajnikant Web Site

    Address: http://rajnikanth.com

    Ha!! Ha!! Ha!!

    Address: http://rajnikanth.com

    Yanna!! Rascala!! Trying to find me Online!!

    Go Offline!! I tell you!!

    Offline/Online Events
    if (navigator.onLine) {
       console.log("You are online
    }
    else {
        console.log("You are offline");
    }
    
    window.addEventListener("offline", function (e) {
       console.log("You are offline");
    }, false);
    
    window.addEventListener("online", function (e) {
        console.log("You are online");
    
    }, false);
            
    Manifest Cache

    This WebSite can work even when you go offline, due to a file manifest.cache

    CACHE MANIFEST
    index.html
    /js/fibonacci.js
    /js/jquery-1.7.2.min.js
    /js/worker.js
    /js/html5shiv-printshiv.js
    /js/modernizr.js
    /js/html5shiv.js
    /js/slides.js
    css/slide.css
    fonts/junction.otf
    images/next-slide.svg
    images/prev-slide.svg
    
    NETWORK:
    
    FALLBACK:
    
    
    Geo & Device Sensor

    Map Demo using geo location

    Device Orientation Demo

    Alpha
    ..
    Beta
    Gamma
    Geo - Code
    //Succes callback
    function success(position) {
        console.log("Position is "+ position.coords.latitude+" , "+position.coords.longitude);
    }
    
    //Failure callback
    function error(errorMsg) {
        console.log("Got Error " + errorMsg.message );
    }
    
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    } else {
        error('not supported');
    }
    
            
    Sensors - Code
    window.addEventListener("deviceorientation", function (event) {
        console.log("alpha :"+event.alpha);
        console.log("beta :"+event.beta);
        console.log("gamma :"+event.gamma);
    });
            
    FileSystem & Drag and Drop

    Run Chrome with argments: --args --unlimited-quota-for-files --allow-file-access-from-files

    Drag and Drop files below
    File D&D - Code
    <div id="dropbox"></div>
    
    var dropbox = document.getElementById("dropbox");
    dropbox.addEventListener("dragenter", dragEnter, false);
    dropbox.addEventListener("dragexit", dragExit, false);
    dropbox.addEventListener("dragover", dragOver, false);
    dropbox.addEventListener("drop", drop, false);
    
    function dragEnter(evt) {
        evt.stopPropagation();
        evt.preventDefault();
    }
    
    function drop(evt) {
        event.stopPropagation();
        event.preventDefault();
        if (evt.dataTransfer.files) {
            var files = event.dataTransfer.files;
            for (var index = 0; index < files.length; index++) {
                //Get the file Object
                var file = files[index];
                console.log("Dropped "+file.name);
            }
        }
    }
    File API - Code

    Initialing File System

    function onInitFs(fs) {
        console.log("File System initiated");
        window.fileSys = fs;
    }
    
    function errorHandler(err) {
        console.log("Unable to initiate fs, got error code " + err.code);
    }
    
    window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
    
    window.requestFileSystem(window.TEMPORARY, 5242880, onInitFs, errorHandler);
            
    File API - Code

    Listing File

    fileSys.root.getDirectory("/",{create:false},
                        function (dirEntry) {
                            dirReader = dirEntry.createReader();
                            dirReader.readEntries(function (entries) {
                                for (var index = 0; index < entries.length; index++) {
                                    var isFile = entries[index].isFile;
                                    var fileName = entries[index].name;
                                    var type = isFile?"File":"Dir";
                                    console.log(type+"  : "+fileName);
                                }
                            },
                            errorHandler);
                        },
                        errorHandler);
            
    File API - Code

    Create Directory

    fileSys.root.getDirectory(targetDir,
                    {create:true},
                    function (dirEntry) {
                        console.log("Directory created");
                    },
                    errorHandler);
            
    Problems with HTML 5
    1. Fragmentation of browsers and features
    2. Many Features not supported on many browsers
    3. Where to find this information?
    4. When informed, how to handle this?
    5. How to detect which features and missing or present?
    6. How to Simulate features?
    How to solve them?
      Decision time
    1. Visit http://html5please.com to see which features are safe to be used
    2. Alternatively also visit http://html5test.com to see which features are safe to be used
      Development time
    1. Make use of Modernizer http://modernizr.com/ Library
    2. Make use of Polyfills (polyfill (n): a JavaScript shim that replicates the standard API for older browsers)
    Q & A