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
67 lines (66 loc) • 2.33 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const isString_1 = __importDefault(require("vanillajs-helpers/isString"));
const kebabCase_1 = __importDefault(require("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_1.default(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_1.default(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_1.default(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_1.default(property)
? handleSingleValue(elm, property, value)
: handleMultipleValues(elm, property);
}
exports.default = css;