UNPKG

vanillajs-browser-helpers

Version:

Collection of convenience code snippets (helpers) that aims to make it a little easier to work with vanilla JS in the browser

62 lines (61 loc) 2.02 kB
import isString from 'vanillajs-helpers/isString'; import kebabCase from 'vanillajs-helpers/kebabCase'; const applyValue = (elm, property, value, important) => { const val = value != null ? String(value) : ''; if (important) { const imp = important ? 'important' : undefined; elm.style.setProperty(kebabCase(property), val, imp); } else { elm.style[property] = val; } // This part here is for when the value is a number, // but the property can't accept just a numeric value, // so "px" has to be added if (!Number.isNaN(Number(val)) && elm.style[property] !== val) { applyValue(elm, property, value + 'px', important); } }; const setValue = (elm, property, value) => { let important = false; if (isString(value) && value.includes('!important')) { value = value.split(' ')[0]; important = true; } applyValue(elm, property, value, important); }; /** * Get a given style property. * if value is set (not undefined), it will be set before returning */ const handleSingleValue = (elm, property, value) => { if (value !== undefined) { setValue(elm, property, value); } // Get all computed styles as that gives a more correct value const val = window.getComputedStyle(elm) .getPropertyValue(kebabCase(property)); if (val.includes('px')) { return parseFloat(val); } const numeric = Number(val); return !Number.isNaN(numeric) ? numeric : val; }; /** * Traverse the `propertyMap` and set style on element accordingly */ const handleMultipleValues = (elm, properties) => { if (properties) { Object.entries(properties) .forEach(([key, value]) => { value && setValue(elm, key, value); }); } return window.getComputedStyle(elm); }; function css(elm, property, value) { return isString(property) ? handleSingleValue(elm, property, value) : handleMultipleValues(elm, property); } export default css;