Skip to content

Instantly share code, notes, and snippets.

@arunstan
Last active July 7, 2016 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arunstan/ef6d4200f314dbedcfc9b19841287af4 to your computer and use it in GitHub Desktop.
Save arunstan/ef6d4200f314dbedcfc9b19841287af4 to your computer and use it in GitHub Desktop.
A function to check whether an HTML5 input type is supported based on the corresponding Modernizr code
// doesSupportInputType.js
//
// A function to check whether an HTML5 input type is supported based on the corresponding Modernizr code
//
// Original code https://github.com/Modernizr/Modernizr/blob/master/feature-detects/inputtypes.js
//
// Usage
//
// doesSupportInputType('date')
// ==> true | false
//
// Can be used to check for the below types
// search tel url email datetime date month week time datetime-local number range color
const doesSupportInputType = inputElemType => {
let inputElem, bool, defaultView
let smile = '1)'
const docElement = document
inputElem = docElement.createElement('input')
inputElem.setAttribute('type', inputElemType)
bool = inputElem.type !== 'text' && 'style' in inputElem
// We first check to see if the type we give it sticks..
// If the type does, we feed it a textual value, which shouldn't be valid.
// If the value doesn't stick, we know there's input sanitization which infers a custom UI
if (bool) {
inputElem.value = smile
inputElem.style.cssText = 'position:absolute;visibility:hidden;'
if (/^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined) {
docElement.body.appendChild(inputElem)
defaultView = docElement.defaultView
// Safari 2-4 allows the smiley as a value, despite making a slider
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
// Mobile android web browser has false positive, so must
// check the height to see if the widget is actually there.
(inputElem.offsetHeight !== 0)
docElement.body.removeChild(inputElem);
} else if (/^(search|tel)$/.test(inputElemType)) {
// Spec doesn't define any special parsing or detectable UI
// behaviors so we pass these through as true
} else if (/^(url|email)$/.test(inputElemType)) {
// Real url and email support comes with prebaked validation.
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else {
// If the upgraded input compontent rejects the :) text, we got a winner
bool = inputElem.value != smile;
}
}
return bool
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment