Introduction to HTML5

by Saurabh Sharma

This article discusses the fifth major revision of HTML (Hyper Text Markup Language) aptly called HTML5. It brings to picture some of the advantages of this new specification along with a side by side comparison with earlier ones and highlights bWhat HTML5 has to offer?b


Since HTML's inception, it has been the "language of web", but has been practically unmaintained after HTML4 (1997). It lacked many features which a current generation user expects from the browser experience. Developers had to toil hard to achieve those and that too not without an inevitable help of plug-ins or custom created controls from different vendors.

But even then many features were just impossible to achieve because of a less supportive HTML. Features like hardware interaction with GPS or Wi-Fi devices, concurrent execution of Java Scripts, standardized client side storage support, support for animation and interoperability across browsers are a few that can be identified.

What HTML5 has to Offer?

HTML5 is a set of standards defined for developing web based applications. It might not be used by all the websites but lays the foundation for better support across modern desktops and mobile browsers. It provides many new features and advantages over the earlier versions. The following section highlights a few of them:

  1. Offline Storage
    This new feature allows the storage of persistent app databases and one-time data (like email) on client side. Actually, offline storage is a lot like Google Gearsb" (a proprietary plug-in from Google which allows offline storage of data) without the need for plug-ins to reap its benefits.
  2. Video and Audio Streaming
    A new Video and Audio tag is included in HTML5 with which we can play video or audio on the website without the help of any plug-in. This feature is still in budding stage and is subject to format turmoil. Famous sites like YouTube may skip Flash entirely to bring streaming audio and video, with timed playback and other neat features.
  3. Geolocation
    An API provided now in HTML5, which can find user's location and use it to filter one's search results, weather updates, advertisement and more. It makes your browser location-aware, either by using the available GPS device or Wi-Fi connection.
  4. Smarter Web Forms
    Many new controls are introduced to ease web development woes which will make it easier to build web applications. There are features like wikis, drag-and-drop tools, discussion boards, real-time chat, search front-ends, and other modern web elements into any site, which work the same across browsers
  5. Web Workers
    It introduces a new API called Web Workers using which Java Scripts can run in the background independent of UI thread.
  6. Animation
    This might be a pleasant surprise for the web developers who have worked on the earlier versions of HTML, now Flash like animation can be achieved through HTML5 without the use of any external plug-ins.
  7. Now lets discuss these features in detail.

Client Side Storage

What comes to mind when one hear the word "Client Side Storage"? The answer would be cookie; cookie was one of the way web developer's stored data on client side but it had many limitations like small size, overhead on every request, lack of standardization and the major one was the issue while handling multiple transactions. HTML5 resolves these issues by bringing in new structured Client Side Storage mechanisms like session storage, local storage and database storage. Using these mechanisms developers can store close to 10 Mb of data as compared to allowable limit of 4Kb by cookies.

Let's take a look at these storage mechanisms in detail:

a) Session Storage

Session Storage is designed to resolve the transaction issue that we had with cookies. With this every instance of a website will now be able to add separate session storage. As each page will save and retrieve the data specific to itself there would not be any issues of dirty reads. With cookies this was not the case if a cookie is added by a website then multiple sessions of the same website will point to that cookie which can result in dirty reads. This issue of dirty read is prevalent in ecommerce sites one of the scenario could be this, suppose user is buying some items from two instances of the same site and have added items to the cart. Then at the time of payment items added through one instance will be visible in another which might result is false payment. Session storage uses Storage object to store data on client side which saves data in Key/Value pair, these key/value pairs are stored as a string. If a key doesn't exist for the value we are trying to store, a new key is automatically created. Following example will give you an idea on how simple it is to implement.


sessionStorage: This is an attribute of window object. It is used as a global object in JavaScript or as a sub-object of window which returns an object of type Storage Object How to store:

  function Save() { sessionStorage.mykey = "Any Value"; }

How to retrieve:

  function Get() { if(sessionStorage.mykey ) { } }

b) Local Storage

Local storage works the same way as the session storage as both use the same Storage object, but they differ in implementation. Local storage is designed to have a continual state as compared to session storage where data is lost when the window is closed or the session is ended. User data up to 10 MB can be stored using local storage. Another difference is in the accessibility of the data stored by the local storage this data is session independent and can be accessed by websites working on multiple windows.


localStorage: Similar to sessionStorage it is also an attribute of window object.

How to store:

  function Save() { localStorage.mykey = "Any Value"; } 

How to retrieve:

  function Get() { if(localStorage.mykey) { } }

c) Database Storage

It is a bit surprising to see Database Storage topic coming under Client storage but yes it is true. Using HTML5, developers can now set up a temporary database on the client machine using simple Java Script methods. Using this data can be stored in a structured manner on client side and will not be limited to key value pair. This will provide random access of client side data. This structured database can also be used to provide offline access to the application. Moreover it also supports relational database which will make life easy for developers when working with interrelated data. The API provided for interaction with this kind of storage is asynchronous and also provides transaction abilities. There are many things for which this can be used like storing frequently used data, storing offline data about emails, saved forms, user details etc.. Let's take a look on how to create a client side database using Java Script. A new database can be created by using openDatabase() method and providing these four arguments on the Window object which is the root level object of any browser window.

  • Database Name
  • Database Version
  • Display Name
  • Estimated Size(Bytes)


Create new database object:

  var db = openDatabase("DB Name","1","Display Name","100000");

Freedom From Plug-ins used for Audio and Video

Popular browser plug-ins like Flash and Silverlight enable web developers to place and manage interactive elements on a web page. However, Flash is considered to be a major source of memory leaks and crashes in browsers and this fact is openly stated by Appleb". Moreover, plug-ins like Flash and others don't work on every platform and hence have to be re-written and adapted for every new one. To build a web application that is expected to run on various browsers and platforms, HTML5's video, audio and interaction standards helps you achieve "Freedom from plug-ins".

Video Tag

The introduction of HTML 5's video tag instructs the browser to display your video in a manner very similar to that achieved by placing images in a webpage.

Basic Syntax

Below is a basic example of a video tag in HTML5:


  <video src="videoTest.ogv"></video>

The above tag embeds the video file, 'videoTest.ogv', into a web page. The file should be located in the same directory as the HTML file because the 'src' attribute refers to a local file. In order to reference a video file in another directory which is on the same web server one just needs to provide the complete file path.


  <video src="/MyComputer/Videos/videoTest.ogv"></video>

One can also provide a link for a file placed on another server:


  <video src="http://testsite.com/videoTest.ogv"></video>

There are other settings in the video tag which can be further used to customize videos.


  <video src="videoTest.ogv" width="500" height="350" autoplay controls> 

Your Browser does not support the video tag. </video>

In the above example the width and height properties are set for video. In case you don't want the video playback to appear distorted, ensure that the height and width dimensions are correctly set. The property autoplay ensures that the video plays as soon as the page loads. The property controls specifies that the controls to pause or play the video (etc) are to be displayed. For cases where the video tag is not supported by the browser, as still some browsers don't support all HTML5 features, one can specify custom messages inside the video tag as fallback content.

Using JavaScript, it is possible to create your own interface and control the video element.


  <video src="videoTest.ogv" id="testVideo"></video> 
  JavaScript functions: video = document.getElementById("testVideo");
   //play video 
  //pause video 
  video.pause(); /
  //seek to second 10 in the video
  video.currentTime = 10;

The HTML5 video tag has many advantages over Flash. Firstly, it is supported on mobile platforms such as the popular Apple iPhone - which doesn't support Flash. Secondly, it alleviates the need for users to install yet another browser plug-in just to play video. Currently, the major browsers which support the video tag are Mozilla Firefox 3.5, Google Chrome 3.0 and their higher versions. Internet Explorer 8 (IE 8) does not support the video tag, though the upcoming IE 9 will support it.

YouTube- Google's popular video web site, is currently experimenting with HTML5 support for videos. A separate link has been provided on the web site which will redirect to the HTML5 video player (instead of the Flash player). With this move from Google, HTML5 video is almost certain to become the most popular technology for displaying videos on the web.

Audio Tag

Using the HTML5's audio tag is also as simple as using the video tag explained above.


  <audio src="audioTest.ogg" controls="controls"> </audio>

The Audio tag allows the playback of audio on you web sites which was earlier achieved by using 3rd party plug-ins like windows media playerb", QuickTimeb" player, Flash etc.


Geolocation refers to the geographic location of an internet connected device. It is another brilliant feature catered to by HTML5. This new API provides details about the current position of the device which is hosting the browser, it can either be a laptop or any handheld device connected to the internet. This new feature is being standardized by a group known as the Geolocation Working Group which is different from the group working on HTML5 standardization, but both are part of W3C. As both HTML5 and Geolocation are being implemented side by side in browsers, geolocation is considered as another HTML5 feature. Geolocation can use any of the available sources like Global Positioning System (GPS) or locations deduced from network variables like RFID, IP address, Wi-Fi and Bluetooth Mac IDs or mobile phone towers and handset IDs to get the position attributes. The Geolocation feature is currently being used in Apple iPad and iPhone along with the Google Android phone. Many browsers like Mozilla Firefox (3.5+), Chrome, Opera and Safari also support the Geolocation APIs.

Now let's dig deep into this API to check out what all it provides. This API provides a new object called Geolocation. It is used by scripts to programmatically determine the location information associated with the hosting device. This location information is used to create and populate the Position object which provides the longitude and latitude value along with other variables.

The Geolocation object provides three functions:

  1. getCurrentPosition This is used to retrieve the current position of the hosting device.
  2. watchCurrentPosition This is used to provide any previously cached position if available and repeatedly keep track of a new position. Using this, continuous details about the position can be obtained when tracking moving objects. This returns a unique watch id for every new watch triggered.
  3. clearWatch This is used to stop or clear a watch on the device by passing the unique watch identifier, when one no longer wishes to track the positional attributes.

Both getcurrentPosition and watchCurrentposition have two callbacks - one for success and one for error. They take Position object as parameter which provides the details about the current position. These callbacks are triggered based on successful and unsuccessful retrieval of Position object respectively.

In a successful call back, the Position object can be used to get the positional attributes.

Example: How to implement Geolocation:

   if (navigator.geolocation) // Check if geolocation is supported by browser 
  // Use getCurrentPosition method to get current position navigator.geolocation.getCurrentPosition(function (position)
   alert(position.coords.latitude + ", " + position.coords.longitude); 
  } ); 
  else { alert ("Your browser does not support Geolocation!!"); }

As per the API specifications, the user will first be prompted for confirmation in a pop up window before sharing the location with the server. A user can either accept or reject sharing of one's geographic location.

Web Workers

Web developers need to strive hard to create rich user experiences and responsive user interfaces using HTML and client side scripting. Java Scripts is the heart of client side programming. Being single threaded, it can perform only one task at a time. HTML5 introduces Web Workers; a web worker defines an API to run Java Scripts in background. Developers generally avoid doing heavy computational tasks using Java Script as it would use the UI thread to execute the task, thereby not being responsive to user interface events. Now, using web workers in HTML5, Java Scripts can be executed on a background thread which will result in a responsive UI even when a heavy background task is in progress. It will also equip developers with multitasking where different Web Workers can work on unrelated Java Scripts simultaneously. It would bring many benefits as heavy computational tasks can be performed by Java Script and in the mean time user can continue working on the web site. With the help of this feature animations can be easily rendered on the page which requires high computation. For example a motion detection application made using Java Script running on Web Worker thread could be used for detecting the movement of objects by monitoring the change of pixels definition in video. This would enable identification of moving object or persons. Now let's see how to use these workers.

Example: How to implement Workers:

  Function testWorker() { if(checkWorkers()){ //Creates and starts a worker, this returns a worker object var worker = new Worker("testScript.js"); // Call back message when postMessage() is called on the testScript.js worker.onmessage = function (event) { document.getElementById('lableTest').textContent = event.data; }; } else{ Alert("Your browser does not support workers"); } } Function checkWorkers() { return !window.Worker; //Worker property is undefined if browser does not support. }


HTML5 specs now include the Canvas API, which is a low level API for drawing. Canvas is a new HTML element which can be used to draw graphics using scripting (usually Java Script). It can for instance be used to draw lines, curves, circles, and polygons and also fill them in with colors and gradients. Also, one can create text and perform numerous types of geometric transformations to anything which is placed on the Canvas. For years, both Mozilla Firefox and Safari have supported canvas tag and the graphics developed using it ran successfully on them. But now, the canvas would be a part of HTML5 specs, which would be used to create graphic intensive web applications for all HTML5 supported browsers.

Following few simple example codes describes how to draw the desired shape/graphics using the canvas element object.

Create a canvas:

  <canvas id="testCanvas" width="300" height="225"></canvas>

Drawing Rectangles

Following is the markup to be placed in the HTML file:

  // Below is the Java Script code for fetching the object and the context function draw_b() { var varCanvas = document.getElementById("testCanvas"); var varContext = varCanvas.getContext("2d"); varContext.fillRect(40, 20, 150, 100); } By Calling fillRect() method a rectangle is drawn and is filled with the current fill style, which is by default black. The rectangle is bounded by its upper-left corner (40, 20), its width (150), and its height (100)

Drawing straight lines

For drawing vertical lines:- context.moveTo(x, 0); context.lineTo(x, 375); For drawing horizontal lines:- context.moveTo(0, y); context.lineTo(500, y);

The inclusion of Canvas in HTML5 makes it one of the most interesting features of this new specification, and it's ready to be used & embraced by most modern Web browsers as it is now a part of HTML5 specs. It will empower the web developer to create games, user interface enhancements, graphic images etc. The 2D context API includes a wealth of functionality which could be further explored and cannot be covered in its entirety here.

This article was originally published on Wednesday Oct 20th 2010
Mobile Site | Full Site