4

How do I detect if the browser supports HTML5 data attribute using Modernizr?

Diogo Cardoso
  • 21,637
  • 26
  • 100
  • 138

1 Answers1

6

Test whether an element has the property dataset.

Modernizr.addTest('data', function () {
    var elem = document.createElement('div');
    return !!elem.dataset;
});
Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
  • 5
    `!!` just ensures that the value returned is either `true` or `false`, rather than, say, `undefined` which evaluates to `false` or `function(){/* code */}`, which evaluates to `true` when treated as a boolean. – cmptrgeekken Jun 04 '11 at 22:05
  • 1
    Yep. In an unsupporting browser elem.dataset = undefined. !undefined = true. !true = false. So !!elem.dataset returns false in an unsupported browser. In a supported one it returns a DOMStringMap, which is a not a falsy value. ! that = false, !false = true. – Rich Bradshaw Jun 04 '11 at 23:08
  • @Rich How do you put this into use in `if` statement? In other words I want to perform an action if this is true and another if it is false. Do you do that inside or outside the `.addTest` function? – ryanve Aug 13 '11 at 16:33
  • 1
    Run that first, then it will make the variable Modernizr.data, which is a boolean. It also adds the class "data" to the html element, for CSS, if needed. – Rich Bradshaw Aug 13 '11 at 20:19