Last active
July 7, 2016 20:41
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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