Tips & Tricks

Detect HTML5 Features

HTML5 is taking major market share nowadays, there are number of good features released with HTML5 which can help us to make the web better place. Most of the features are available in all major latest browsers so we can use most of the features. But the fact is we should not forget old browsers (atleast for sometime) when we have new version or latest browsers are available.

HTML5 Feature Detection

Now another fact is client will always want new things but still want to support old ones. So to build such product which works cross browser, only thing we can do is feature detection of HTML5. So certain code should only execute when particular feature is available in browser.

[gads]

We have Modernizr available which is very good JS library to perform feature detection of HTML5 and CSS3. This library will perform detection for all features by default (you can customize ofcourse), but if you are looking to perform detection of any particular feature and not want to include whole library you are at right place. Yes in this article we will see how we can detect HTML5 features with pure vanila JS and with Modernizr as well.

Canvas

[cc lang=”js”]
// JS
return !!document.createElement(‘canvas’).getContext;

// Modernizr
if (Modernizr.canvas) {

}
[/cc]

Video

[cc lang=”js”]
// JS
return !!document.createElement(‘video’).canPlayType;

// Modernizr
if (Modernizr.video) {

}
[/cc]

Local Storage

[cc lang=”js”]
// JS
return ‘localStorage’ in window && window[‘localStorage’] !== null;

// Modernizr
if (Modernizr.localstorage) {

}
[/cc]

Web Workers

[cc lang=”js”]
// JS
return !!window.Worker;

// Modernizr
if (Modernizr.webworkers) {

}
[/cc]

Offline Web Application

[cc lang=”js”]
// JS
return !!window.applicationCache;

// Modernizr
if (Modernizr.applicationcache) {

}
[/cc]

[gads]

Geolocation

[cc lang=”js”]
// JS
return ‘geolocation’ in navigator;

// Modernizr
if (Modernizr.geolocation) {

}
[/cc]

Placeholder Text

[cc lang=”js”]
// JS
var i = document.createElement(‘input’);
return ‘placeholder’ in i;

// Modernizr
if (Modernizr.input.placeholder) {

}
[/cc]

Form Autofocus

[cc lang=”js”]
// JS
var i = document.createElement(‘input’);
return ‘autofocus’ in i;

// Modernizr
if (Modernizr.input.autofocus) {

}
[/cc]

Microdata

[cc lang=”js”]
// JS
return !!document.getItems;

// Modernizr does not provide support to detect Microdata
[/cc]

History API

[cc lang=”js”]
// JS
return !!(window.history && history.pushState);

// Modernizr
if (Modernizr.history) {

}
[/cc]

So this was the feature list I have collected so far, let me know if you have any more feature detection to share in this list?

Shares:
  • John D
    John D
    August 8, 2014 at 5:58 pm

    Nice Collection dude, will make handy :)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *