Instantly share code, notes, and snippets.

@tomhodgins tomhodgins/prinCSS.html
Last active Sep 1, 2017

Embed
What would you like to do?
prinCSS - a Simple JS in CSS pattern that can be implemented in a flexible way (with bonus container queries mixin!) http://staticresource.s3.amazonaws.com/princss.html
<!DOCTYPE html>
<meta charset=utf-8>
<meta name=viewport content="width=device-width, initial-scale=1">
<title>prinCSS - a simple JS in CSS Pattern</title>
<nav>
<input type=button value="Add prinCCS" onclick=addPrinCSS()>
<input type=button value="Remove prinCSS" onclick=removePrinCSS()>
</nav>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<input placeholder="Type 5 or more characters">
<script>
function addPrinCSS() {
window.addEventListener('load', debounce)
window.addEventListener('resize', debounce)
window.addEventListener('input', debounce)
window.addEventListener('click', debounce)
}
function removePrinCSS() {
var tag = document.querySelector('#prinCSS')
if (tag) {
tag.remove()
}
window.removeEventListener('load', debounce)
window.removeEventListener('resize', debounce)
window.removeEventListener('input', debounce)
window.removeEventListener('click', debounce)
}
function prinCSS(tag) {
var tag = document.querySelector('#prinCSS')
if (!tag) {
tag = document.createElement('style')
tag.id = 'prinCSS'
document.head.appendChild(tag)
}
return tag.innerHTML = `
body:before {
content: '${innerWidth} x ${innerHeight}';
position: fixed;
right: 0;
}
${cq('input', 'this.value.length >= 5', '', `
background: lime;
`)}
${cq('div', 'this.offsetWidth >= 800', 'p', `
color: orange;
`)}
`
}
// Debounced execution
var delay = timer = 10
var bouncing = false
function debounce() {
if (timer === delay) {
if (!bouncing) {
bouncing = true
prinCSS()
var countdown = setInterval(function() {
timer--
if (timer <= 0) {
bouncing = false
clearInterval(countdown)
timer = delay
prinCSS()
}
}, 1)
}
}
}
// Container Queries Mixin
function cq(selectorList, query, childSelector, rule) {
var style = ''
var count = 0
document.querySelectorAll(selectorList).forEach(tag => {
var attr = btoa(selectorList).replace(/[= "'>+]/g, '')
var func = new Function('return ' + query)
if (func.call(tag)) {
tag.setAttribute(`cq-${attr}`, count)
style += `
[cq-${attr}="${count}"] ${childSelector} {
${rule}
}
`
count++
} else {
tag.setAttribute(`cq-${attr}`, '')
}
})
return style
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment