Last active
May 10, 2022 01:13
-
-
Save ezakto/2640245e6a5e89efe4eb to your computer and use it in GitHub Desktop.
Dynamic CSS templates
This file contains 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
function CSSTemplate(stylesheet) { | |
var styles = document.getElementById(stylesheet); | |
var source = styles.innerHTML.split('$'); | |
var _cache = {}; | |
this.set = function(hash) { | |
styles.innerHTML = source.map(function(chunk){ | |
var key, re; | |
for (key in hash) { | |
_cache[key] = hash[key]; | |
re = new RegExp('^'+key+'\\b'); | |
if (re.test(chunk)) { | |
return chunk.replace(re, _cache[key]); | |
} | |
} | |
return chunk.replace(/^.+?\b/, ''); | |
}).join(''); | |
}; | |
}; |
This file contains 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
function CSSTemplate(a){var b=document.getElementById(a),c=b.innerHTML.split("$"),d={};this.set=function(a){b.innerHTML=c.map(function(b){var c,e;for(c in a)if(d[c]=a[c],e=new RegExp("^"+c+"\\b"),e.test(b))return b.replace(e,d[c]);return b.replace(/^.+?\b/,"")}).join("")}} |
This file contains 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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>CSS templates</title> | |
<style id="css-tpl"> | |
body { | |
font-size: $fontsize; | |
} | |
.full-height { | |
height: $windowheight; | |
} | |
</style> | |
<script src="csstemplate.js"></script> | |
<script> | |
var css = new CSSTemplate('css-tpl'); | |
var handler = function(){ | |
css.set({ | |
fontsize: (window.innerHeight / 5) + 'px', | |
windowheight: window.innerHeight + 'px' | |
}); | |
}; | |
handler(); | |
window.addEventListener('resize', handler); | |
</script> | |
</head> | |
<body> | |
<div>Hello, world!</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment