Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect whether an HTML5 input control is supported?

If I put a <input type="range"> control on a form, some browsers will (correctly) render a slider control, and others won't know what range is and will render a textbox instead. Handling this case would require extra validation, as a textbox can contain any arbitrary text. Is there any JavaScript I can put into the page to say "look at this control in the DOM, and if it's a textbox control, do foo()"?

like image 867
Mason Wheeler Avatar asked Apr 10 '13 00:04

Mason Wheeler


People also ask

What are HTML5 controls?

The HTML5 controls attribute when used on either <audio> or <video> element, it adds few controls on the browser. The controls added are play/pause, volume , seeking and mute/ unmute. A full screen button will be added for video and CC, track buttons if the author provides.


1 Answers

This site recommends using Modernizer:

Checking for HTML5 input types uses detection technique #4. First, you create a dummy <input> element in memory. The default input type for all <input> elements is "text". This will prove to be vitally important.

var i = document.createElement("input");

Next, set the type attribute on the dummy element to the input type you want to detect.

i.setAttribute("type", "color");

If your browser supports that particular input type, the type property will retain the value you set. If your browser doesn't support that particular input type, it will ignore the value you set and the type property will still be "text".

return i.type !== "text";

Instead of writing 13 separate functions yourself, you can use Modernizr to detect support for all the new input types defined in HTML5. Modernizr reuses a single <input> element to efficiently detect support for all 13 input types. Then it builds a hash called Modernizr.inputtypes, that contains 13 keys (the HTML5 type attributes) and 13 Boolean values (true if supported, false if not).

//check for native date picker
if (!Modernizr.inputtypes.date) {
  // no native support for <input type="date"> :(
  // maybe build one yourself with Dojo or jQueryUI
}
like image 200
John Conde Avatar answered Sep 21 '22 23:09

John Conde