# HTML5

## The Future of Web

Narasing Rao Akula
Technology Head of ECM & Mobility Solutions, Virtusa

###

- Narasing Rao Akula
- Enterprise Architect, experience: 16 years
- Technology Head – ECM & Mobility Solutions
- http://www.linkedin.com/in/narasing

HTML5 ~= HTML + CSS + JS

HTML5 refers to the family of these technologies.

###

- Offline / Storage
- Realtime / Communication
- File / Hardware Access
- Semantics & Markup
- Graphics / Multimedia
- Nuts & Bolts

## Offline / Storage

Expect the unexpected

###

- Keep yourself organized for
- ...instant retrieval of structured data
- Reduce network requests as
- ...bandwidth is expensive!
- Better Performance

#### `window.localStorage`

- Key / value pairs - hash table
- Persistent on page reloads & window reopen
- Avoids HTTP overhead of cookies
- Great for storing user preferences

    localStorage.setItem('someKey', someValue);
    localStorage.getItem('someKey'); // value

    // Can also access as a property, but not recommended.
    localStorage.someKey = someValue;

#### `window.sessionStorage`

Same as `localStorage` but...

- Lasts as long as browser is open
- Opening page in new window or tab starts new session
- Great for sensitive data (e.g. banking sessions)

    // use localStorage for persistent storage
    // use sessionStorage for per tab storage
    saveButton.addEventListener('click', function () {
      window.localStorage.setItem('value', area.value);
      window.localStorage.setItem('timestamp', (new Date()).getTime());
    }, false);
    textarea.value = window.localStorage.getItem('value');

Save text value on the client side (crash-safe)

This specification is no longer in active maintanance

    var db = window.openDatabase("DBName", "1.0", "description", 5*1024*1024); //5MB
    db.transaction(function(tx) {
      tx.executeSql("SELECT * FROM test", [], successCallback, errorCallback);
    });

See the generated database: Developer > Developer Tools > Storage

    var idbRequest = window.indexedDB.open('Database Name');
    idbRequest.onsuccess = function(event) {
      var db = event.srcElement.result;
      var transaction = db.transaction([], IDBTransaction.READ_ONLY);
      var curRequest = transaction.objectStore('ObjectStore Name').openCursor();
      curRequest.onsuccess = ...;
    };

Object store not yet created.

## Realtime / Communication

Stay connected

#### `Without Web Workers:`

- Long-running JavaScript tasks can block other JavaScript on the page
- JavaScript can cause some browser UIs to hang

#### `With Web Workers:`

- Background processing capabilities to web applications can be added
- Parallel operations can run concurrently

#### `Web Workers are used for`

- Background number-crunchers
- Background notification from server to a local database
- Background price updates from server
- Search queries

main.js:

    var worker = new Worker('task.js');
    worker.onmessage = function(event) { alert(event.data); };
    worker.postMessage('data');

task.js:

    self.onmessage = function(event) {
      // Do some work.
      self.postMessage("recv'd: " + event.data);
    };

Loading Route...

Try dragging the map while the complex route is being calculated (you will only be able to do that with Workers!)

    var socket = new WebSocket('ws://html5rocks.websocket.org/echo');
    socket.onopen = function(event) {
      socket.send('Hello, WebSocket');
    };
    socket.onmessage = function(event) { alert(event.data); }
    socket.onclose = function(event) { alert('closed'); }

Full-duplex, bi-directional communication over the Web: Both the server and client can send data at any time, or even at the same time. Only the data itself is sent, without the overhead of HTTP headers, dramatically reducing bandwidth.

Use the echo demo below to test a WebSocket connection from your browser. Both the message you send and the response you receive travel over the same WebSocket connection.

#### Location:

Use secure WebSocket (TLS/SSL)

#### Message:

Output:
Demo powered by

    if (window.webkitNotifications.checkPermission() == 0) {
      // you can pass any url as a parameter
      window.webkitNotifications.createNotification(tweet.picture, tweet.title,
          tweet.text).show();
    } else {
      window.webkitNotifications.requestPermission();
    }

Note: Use this button if you also want to reset the permissions

Enter your twitter user name to show your last tweet as a notification

## File / Hardware Access

Deeper integration with the Operating System

    document.addEventListener('dragstart', function(event) {
      event.dataTransfer.setData('text', 'Customized text');
      event.dataTransfer.effectAllowed = 'copy';
    }, false);

2. Select text and drag (original text will be dropped)
3. Select text and drag (dragged text data will be altered from original)

Source Data
Drop Area

### Drag files in from the desktop:

    document.querySelector('#dropzone').addEventListener('drop', function(e) {
      var reader = new FileReader();
      reader.onload = function(evt) {
        document.querySelector('img').src = evt.target.result;
      };

      reader.readAsDataURL(e.dataTransfer.files[0]);
    }, false);

Drop in images from your desktop

    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        var latLng = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude);
        var marker = new google.maps.Marker({position: latLng, map: map});
        map.setCenter(latLng);
      }, errorHandler);
    }

    <input type="text" x-webkit-speech />

Speech input is not enabled in your browser.
Try running Google Chrome with the `--enable-speech-input` flag.

## Semantics & Markup

More meaningful elements

    <body>
      <header>
        <hgroup>
          <h1>Page title</h1>
          <h2>Page subtitle</h2>
        </hgroup>
      </header>

      <nav>
       <ul>
         Navigation...
       </ul>
      </nav>
      <section>
       <article>
         <header>
           <h1>Title</h1>
         </header>
         <section>
           Content...
         </section>
       </article>
       <article>
         <header>
           <h1>Title</h1>
         </header>
         <section>
           Content...
         </section>
       </article>
      </section>

      <aside>
       Top links...
      </aside>

      <figure>
        <img src="..."/>
        <figcaption>Chart 1.1</figcaption>
      </figure>

      <footer>
       Copyright ©
       <time datetime="2010-11-08">2010</time>.
      </footer>
    </body>

    <input list="cars"/>
    <datalist id="cars">
      <option value="BMW"/>
      <option value="Ford"/>
      <option value="Volvo"/>
    </datalist>

    <menu>
      <command type="command" disabled label="Publish" />
    </menu>

    <details>
      <summary>HTML 5</summary>
      This slide deck teaches you everything you need to know about HTML 5.
    </details>
    HTML 5This slide deck teaches you everything you need to know about HTML 5.

    <meter min="0" max="100" low="40" high="90" optimum="100" value="91">A+</meter>
    Your score is: A+

    <progress>working...</progress>
    Download is: working...

    <progress value="75" max="100">3/4 complete</progress>
    Goal is: 3/4 complete

    <style>
      [required] {
        border-color: #88a;
        -webkit-box-shadow: 0 0 3px rgba(0, 0, 255, .5);
      }
      :invalid {
        border-color: #e88;
        -webkit-box-shadow: 0 0 5px rgba(255, 0, 0, .8);
      }
    </style>

    <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="search" results="10" placeholder="Search..." />

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

    type="text"

Android Device

    type="number"

Android Device

    type="email"

iPhone Device

    type="tel"

iPhone Device

## Graphics / Multimedia

2D & 3D

    <audio id="audio" src="sound.mp3" controls></audio>
    document.getElementById("audio").muted = false;

    <video id="video" src="movie.webm" autoplay controls></video>
    document.getElementById("video").play();

Your browser does not support the video tag
Your browser does not support the audio tag

    <canvas id="canvas" width="838" height="220"></canvas>

    <script>
      var canvasContext = document.getElementById("canvas").getContext("2d");
      canvasContext.fillRect(250, 25, 150, 100);

      canvasContext.beginPath();
      canvasContext.arc(450, 110, 100, Math.PI * 1/2, Math.PI * 3/2);
      canvasContext.lineWidth = 15;
      canvasContext.lineCap = 'round';
      canvasContext.strokeStyle = 'rgba(255, 127, 0, 0.5)';
      canvasContext.stroke();
    </script>

    <canvas id="canvas" width="838" height="220"></canvas>

    <script>
      var gl = document.getElementById("canvas").getContext("experimental-webgl");
      gl.viewport(0, 0, canvas.width, canvas.height);
      ...
    </script>

    <html>
      <svg>
        <circle id="myCircle" class="important" cx="50%" cy="50%" r="100"
            fill="url(#myGradient)"
            onmousedown="alert('hello');"/>
      </svg>
    </html>

## Nuts & Bolts

Improvements to the core platform

## Finding elements by class (DOM API)

    var el = document.getElementById('section1');
    el.focus();

    var els = document.getElementsByTagName('div');
    els[0].focus();

    var els = document.getElementsByClassName('section');
    els[0].focus();

## Finding elements by CSS syntax (Selectors API)

    var els = document.querySelectorAll("ul li:nth-child(odd)");
    var tds = document.querySelectorAll("table.test > tr > td");
    var el = document.querySelector("table.test > tr > td"); // el == tds[0]

## Define, store, and retrieve custom data on the DOM.

    <div id="out" data-id="good" data-name="joe" data-screen-name="user1"></div>

    // Add new data attributes via JS.
    var el = document.querySelector('#out');
    el.setAttribute('data-foo', 'bar');

    var html = [];
    for (var key in el.dataset) {
      html.push(key, ': ', el.dataset[key], '<br>');
    }

    el.innerHTML = html.join('');

Output:

    id: good
    name: joe
    screenName: user1
    foo: bar

    <div id="main" class="shadow rounded"></div>

    var el = document.querySelector('#main').classList;
    el.add('highlight');
    el.remove('shadow');
    el.toggle('highlight');

    console.log(el.contains('highlight')); // false
    console.log(el.contains('shadow')); // false
    console.log(el.classList.toString() == el.className); // true

Output:

    <div id="main" class="rounded"></div>

    link.addEventListener('click', function(event) {
      // manually add a value to the history stack
      // without making the browser load any new page
      history.pushState('Contact Page Form', 'Contact Page', '/contact');
    });

    // capture navigation in case we want to change,
    // for instance, some content when it changes
    window.addEventListener('popstate', function(event) {
      document.querySelector('h1').innerText = event.state; // 'Contact Page Form'
    });

Thanks
&
Any Questions