Last active
May 31, 2019 22:26
-
-
Save Andy-set-studio/c119528bead18261c424c735a6fb08da to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Pass in an element and its CSS Custom Property that you want the value of. | |
* Optionally, you can determine what datatype you get back. | |
* | |
* @param {String} propKey | |
* @param {HTMLELement} element=document.documentElement | |
* @param {String} castAs='string' | |
* @returns {*} | |
*/ | |
const getCSSCustomProp = (propKey, element = document.documentElement, castAs = 'string') => { | |
let response = getComputedStyle(element).getPropertyValue(propKey); | |
// Tidy up the string if there's something to work with | |
if (response.length) { | |
response = response.replace(/\'|"/g, '').trim(); | |
} | |
// Convert the response into a whatever type we wanted | |
switch (castAs) { | |
case 'number': | |
case 'int': | |
return parseInt(response, 10); | |
case 'float': | |
return parseFloat(response, 10); | |
case 'boolean': | |
case 'bool': | |
return response === 'true' || response === '1'; | |
} | |
// Return the string response by default | |
return response; | |
}; | |
export default getCSSCustomProp; |
This file contains 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
import getCSSCustomProp from 'get-css-custom-prop.js'; | |
const myComponent = document.querySelector('.my-component'); | |
const isSnapSupported = getCSSCustomProp('--supports-scroll-snap', myComponent, 'boolean'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment