Javascript styles
Allow to define css clases in runtime with vanilla javascript
by Yerko Palma
HTML
<button>
No style
</button>
<button class="styled">
Styled!
</button>
Babel + JSX
const sheet = (() => {
// Create the <style> tag
const style = document.createElement('style')
// Add a media (and/or media query) here if you'd like!
style.setAttribute('media', 'screen')
// WebKit hack :(
style.appendChild(document.createTextNode(''))
// Add the <style> element to the page
document.head.appendChild(style)
return style.sheet
})()
function addCSSRule(sheet, selector, rules, index) {
let ruleString = ''
if (typeof rules === 'object') {
ruleString = '{ '
for(let key in rules) {
ruleString += `${key}: ${rules[key]};`
}
ruleString += '}'
} else if (typeof rules === 'string') {
ruleString = `{ ${rules} }`
}
if('insertRule' in sheet) {
sheet.insertRule(`${selector} ${ruleString}`, index);
}
}
function addKeyframeAnimation(sheet, name, rules) {
// make the string
let animation
if (rules.from && rules.to) {
animation =
`@keyframes ${name} {
from {
${rules.from}
}
to {
${rules.to}
}
}`
}
console.log(animation)
if(sheet.hasOwnProperty('insertRule')) {
sheet.insertRule(animation, index)
}
}
const style = {
widht: '100px',
heifht: '50px',
padding: '10px',
'background-color': '#f44336'
}
const animKeyframe = {
from: 'margin-top: 0; background-color: #f44336;',
to: 'margin-top: 20px; background-color: #e91e63;'
}
const animate = {
animation: 'anim 0.3s'
}
addCSSRule(sheet, '.styled', style)
addKeyframeAnimation(sheet, 'anim', animKeyframe)
addCSSRule(sheet, '.animate', animate)
const btn = document.querySelector('.styled')
btn.addEventListener('click', (e) => {
e.target.classList.toggle('animate')
})