Skip to content

Instantly share code, notes, and snippets.

@Andy-set-studio
Last active May 31, 2019 22:26
Show Gist options
  • Save Andy-set-studio/c119528bead18261c424c735a6fb08da to your computer and use it in GitHub Desktop.
Save Andy-set-studio/c119528bead18261c424c735a6fb08da to your computer and use it in GitHub Desktop.
/**
* 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;
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