Created
October 26, 2017 22:52
-
-
Save aleclarson/11c9d310605d42feb5322c4fe8f19241 to your computer and use it in GitHub Desktop.
Javascript-driven CSS rules
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
const capsRE = /([A-Z])/g; | |
const $styles = $('<style>').appendTo(document.head); | |
exports.addRule = function(selector, style) { | |
$styles.append(formatRule(selector, style)); | |
}; | |
function formatRule(selector, style) { | |
return [ | |
selector, | |
' {\n ', | |
css(style).join('\n '), | |
'\n}' | |
].join(''); | |
} | |
function css(style) { | |
return Object.keys(style).map(key => { | |
return key.replace(capsRE, hyphenate) + ': ' + style[key] + ';'; | |
}); | |
} | |
function hyphenate(caps) { | |
return '-' + caps[0].toLowerCase(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Naïve example:
All values are converted into strings verbatim. Thus, you must add
px
manually.Not yet sure how to yield to stylesheets added via
<link rel="stylesheet">
. May not be possible? If not, this solution is best for overriding existing styles.jQuery is used, but not required (obviously).