Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Element Query JS-in-CSS Mixin, you supply a CSS selector, custom conditions, and a stylesheet with $this as a placeholder selector for matching elements. Use like: element('textarea', {minCharacters: 5}, `$this { background: lime; }`)
function element(selector, conditions, stylesheet) {
var features = {
minWidth: function(el, number) { return number <= el.offsetWidth },
maxWidth: function(el, number) { return number >= el.offsetWidth },
minHeight: function(el, number) { return number <= el.offsetHeight },
maxHeight: function(el, number) { return number >= el.offsetHeight },
minChildren: function(el, number) { return number <= el.children.length },
maxChildren: function(el, number) { return number >= el.children.length },
minCharacters: function(el, number) { return number <= ((el.value && el.value.length) || el.textContent.length) },
maxCharacters: function(el, number) { return number >= ((el.value && el.value.length) || el.textContent.length) },
minScrollX: function(el, number) { return number <= el.scrollLeft },
maxScrollX: function(el, number) { return number >= el.scrollLeft },
minScrollY: function(el, number) { return number <= el.scrollTop },
maxScrollY: function(el, number) { return number >= el.scrollTop },
minAspectRatio: function(el, number) { return number <= el.offsetWidth / el.offsetHeight },
maxAspectRatio: function(el, number) { return number >= el.offsetWidth / el.offsetHeight },
orientation: function(el, string) {
switch (string) {
case 'portrait': return el.offsetWidth < el.offsetHeight
case 'square': return el.offsetWidth == el.offsetHeight
case 'landscape': return el.offsetWidth > el.offsetHeight
}
}
}
var tag = document.querySelectorAll(selector)
var generatedStyles = ''
var count = 0
for (var i=0; i<tag.length; i++) {
var results = []
var conditionList = []
var testList = []
for (condition in conditions) {
if (conditions.hasOwnProperty(condition)) {
conditionList.push(condition)
testList.push(conditions[condition])
}
}
var identifier = (selector + conditionList + testList).replace(/\W/g, '')
for (test in conditions) {
results.push(features[test](tag[i], conditions[test]) ? true : false)
}
if (results.indexOf(false) == -1) {
tag[i].setAttribute('data-' + identifier, count)
generatedStyles += stylesheet.replace(/:self|\$this/g, '[data-' + identifier + '="' + count + '"]')
count++
} else {
tag[i].setAttribute('data-' + identifier, '')
}
}
return generatedStyles
}
const element = (selector, conditions, stylesheet) => {
const features = {
minWidth: (el, number) => number <= el.offsetWidth,
maxWidth: (el, number) => number >= el.offsetWidth,
minHeight: (el, number) => number <= el.offsetHeight,
maxHeight: (el, number) => number >= el.offsetHeight,
minChildren: (el, number) => number <= el.children.length,
maxChildren: (el, number) => number >= el.children.length,
minCharacters: (el, number) => number <= ((el.value && el.value.length) || el.textContent.length),
maxCharacters: (el, number) => number >= ((el.value && el.value.length) || el.textContent.length),
minScrollX: (el, number) => number <= el.scrollLeft,
maxScrollX: (el, number) => number >= el.scrollLeft,
minScrollY: (el, number) => number <= el.scrollTop,
maxScrollY: (el, number) => number >= el.scrollTop,
minAspectRatio: (el, number) => number <= el.offsetWidth / el.offsetHeight,
maxAspectRatio: (el, number) => number >= el.offsetWidth / el.offsetHeight,
orientation: (el, string) => {
switch (string) {
case 'portrait': return el.offsetWidth < el.offsetHeight
case 'square': return el.offsetWidth == el.offsetHeight
case 'landscape': return el.offsetWidth > el.offsetHeight
}
}
}
let generatedStyles = ''
let count = 0
document.querySelectorAll(selector).forEach(tag => {
const identifier = (selector
+ Object.keys(conditions)
+ Object.values(conditions)).replace(/\W/g, '')
let results = []
for (test in conditions) {
results.push(features[test](tag, conditions[test]) ? true : false)
}
if (results.indexOf(false) == -1) {
tag.setAttribute(`data-${identifier}`, count)
generatedStyles += stylesheet.replace(/:self|\$this/g, `[data-${identifier}="${count}"]`)
count++
} else {
tag.setAttribute(`data-${identifier}`, '')
}
})
return generatedStyles
}
<!DOCTYPE html>
<meta charset=utf-8>
<meta name=viewport content="width=device-width, initial-scale=1">
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel=stylesheet>
<link href=http://staticresource.com/data-buttons.css rel=stylesheet>
<title>Element Query Mixin Test</title>
<style>
body style {
display: block;
width: 100%;
padding: 1em;
margin: 1em 0 2em 0;
border-radius: 3px;
font-size: 12pt;
font-family: 'Source Code Pro', Consolas, 'Andale Mono WT', 'Andale Mono', 'Lucida Console', 'Lucida Sans Typewriter', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Liberation Mono', 'Nimbus Mono L', Monaco, 'Courier New', Courier, monospace;
word-break: break-word;
white-space: pre-wrap;
font-kerning: auto;
color: rgba(0,0,0,.7);
background: transparent;
border: 1px solid rgba(0,0,0,.3);
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-kerning: auto;
}
body {
margin: 1em;
font-family: 'Source Sans Pro', sans-serif;
}
[data-button] {
display: block;
margin: 1em 0;
}
div {
display: inline-block;
border-radius: .2em;
padding: 1.5em;
color: #555;
font-size: 12pt;
line-height: 1.4;
background: #eee;
border: 1px solid #ccc;
}
input,
textarea {
display: block;
min-width: 250px;
border-radius: .2em;
margin: 1em;
padding: .5em;
color: #555;
font-size: 12pt;
background: white;
border: 1px solid #ccc;
}
section {
height: 300px;
display: inline-block;
border: 1px dotted black;
padding: 1em;
}
img {
max-width: 50px;
box-shadow: rgba(0,0,0,.1) 0 .2em .5em;
}
img + img {
margin-left: 1em;
}
p {
font-size: 10pt;
color: #555;
}
[class*=-scroll-x] {
overflow-x: scroll;
}
[class*=-scroll-x] p {
width: 200%;
}
[class*=-scroll-y] {
height: 100px;
overflow-y: scroll;
}
/* Drag Handles */
[data-nubbin] {
border: 1px solid rgba(0,0,0,.15);
width: 30px;
height: 30px;
text-align: center;
padding: 0;
margin: 0;
background: yellow;
cursor: pointer;
z-index: 500;
}
[data-nubbin] i {
pointer-events: none;
color: black;
line-height: 30px;
font-size: 20px;
}
[data-drag] {
overflow: auto;
}
[data-drag=horizontal] {
resize: horizontal;
}
[data-drag=vertical] {
resize: vertical;
}
[data-drag=both] {
resize: both;
}
#ew, #eh, #emin, #emax {
min-width: 100px;
min-height: 100px;
width: 500px;
max-width: 100vw;
max-height: 100vh;
}
</style>
<h1>Element Query Mixin Test</h1>
<h2>Width Queries</h2>
<h3>min-width</h3>
<div class=minwidth data-drag=horizontal>class="minwidth"</div>
<h3>max-width</h3>
<div class=maxwidth data-drag=horizontal>class="maxwidth"</div>
<h2>Height Queries</h2>
<h3>min-height</h3>
<div class="minheight" data-drag=vertical>class="minheight"</div>
<h3>max-height</h3>
<div class="maxheight" data-drag=vertical>class="maxheight"</div>
<h2>Quantity Queries</h2>
<h3>min-characters on block elements</h3>
<p>(Use keyboard)</p>
<div class="mincharacters" contenteditable>class="mincharacters"</div>
<h3>min-characters on form inputs</h3>
<p>(Use keyboard)</p>
<input type=text class="mincharacters-input" value='class="mincharacters-input"'>
<textarea class="mincharacters-textarea">class="mincharacters-textarea"</textarea>
<h3>max-characters on block elements</h3>
<p>(Use keyboard)</p>
<div class="maxcharacters" contenteditable>class="maxcharacters"</div>
<h3>max-characters on form inputs</h3>
<p>(Use keyboard)</p>
<input type=text class="maxcharacters-input" value='class="maxcharacters-input"'>
<textarea class="maxcharacters-textarea">class="maxcharacters-textarea"</textarea>
<h3>min-children</h3>
<button data-button="semiflat" onclick="var img=document.createElement('img');img.src='http://staticresource.s3.amazonaws.com/user.png';document.querySelector('.minchildren').appendChild(img);JSinCSS.apply()">Add Child</button>
<div class="minchildren">
<img src=http://staticresource.s3.amazonaws.com/user.png style=width:50px>
</div>
<h3>max-children</h3>
<button data-button="semiflat" onclick="var img=document.createElement('img');img.src='http://staticresource.s3.amazonaws.com/user.png';document.querySelector('.maxchildren').appendChild(img);JSinCSS.apply()">Add Child</button>
<div class="maxchildren">
<img src=http://staticresource.s3.amazonaws.com/user.png style=width:50px>
</div>
<h2>Scroll queries</h2>
<h3>min-scroll-y</h3>
<div class="min-scroll-y" onscroll=JSinCSS()>
<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>
<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>
<h3>max-scroll-y</h3>
<div class="max-scroll-y" onscroll=JSinCSS()>
<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>
<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>
<h3>min-scroll-x</h3>
<div class="min-scroll-x" onscroll=JSinCSS()>
<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>
<h3>max-scroll-x</h3>
<div class="max-scroll-x" onscroll=JSinCSS()>
<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>
<h2>Aspect queries</h2>
<h3>orientation</h3>
<div class="square" style="width: 100px; height: 100px;">100 &times; 100</div>
<div class="portrait" style="width: 100px; height: 200px;">100 &times; 200</div>
<div class="landscape" style="width: 200px; height: 100px;">200 &times; 100</div>
<h3>min-aspect-ratio</h3>
<div class="minaspectratio" data-drag=both>class="minaspectratio"</div>
<h3>max-aspect-ratio</h3>
<div class="maxaspectratio" data-drag=both>class="maxaspectratio"</div>
<script>
window.addEventListener('load', JSinCSS)
window.addEventListener('resize', JSinCSS)
window.addEventListener('input', JSinCSS)
window.addEventListener('click', JSinCSS)
function JSinCSS() {
var tag = document.querySelector('#JSinCSS')
if (!tag) {
tag = document.createElement('style')
tag.id = 'JSinCSS'
document.head.appendChild(tag)
}
tag.innerHTML = `
/* Min-width */
${element('.minwidth', {minWidth: 300}, `
.minwidth {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-width in px */
${element('.maxwidth', {maxWidth: 300}, `
.maxwidth {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-height in px */
${element('.minheight', {minHeight: 200}, `
.minheight {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-height in px */
${element('.maxheight', {maxHeight: 200}, `
.maxheight {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-characters on block elements */
${element('.mincharacters', {minCharacters: 35}, `
.mincharacters {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-characters on input */
${element('.mincharacters-input', {minCharacters: 35}, `
.mincharacters-input {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-characters on textarea */
${element('.mincharacters-textarea', {minCharacters: 35}, `
.mincharacters-textarea {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-characters */
${element('.maxcharacters', {maxCharacters: 35}, `
.maxcharacters {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-characters on input */
${element('.maxcharacters-input', {maxCharacters: 35}, `
.maxcharacters-input {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-characters on textarea */
${element('.maxcharacters-textarea', {maxCharacters: 35}, `
.maxcharacters-textarea {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-children */
${element('.minchildren', {minChildren: 5}, `
.minchildren {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-children */
${element('.maxchildren', {maxChildren: 5}, `
.maxchildren {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-scroll-y */
${element('.min-scroll-y', {minScrollY: 50}, `
.min-scroll-y {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-scroll-y */
${element('.max-scroll-y', {maxScrollY: 50}, `
.max-scroll-y {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Min-scroll-x */
${element('.min-scroll-x', {minScrollX: 50}, `
.min-scroll-x {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-scroll-x */
${element('.max-scroll-x', {maxScrollX: 50}, `
.max-scroll-x {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Square Orientation */
${element('.square', {orientation: 'square'}, `
.square {
background: orchid;
}
`)}
/* Portrait Orientation */
${element('.portrait', {orientation: 'portrait'}, `
.portrait {
background: darkturquoise;
}
`)}
/* Landscape Orientation */
${element('.landscape', {orientation: 'landscape'}, `
.landscape {
background: greenyellow;
}
`)}
/* Min-aspect ratio */
${element('.minaspectratio', {minAspectRatio: 16/9}, `
.minaspectratio {
background: greenyellow;
border-color: limegreen;
}
`)}
/* Max-aspect-ratio */
${element('.maxaspectratio', {maxAspectRatio: 16/9}, `
.maxaspectratio {
background: greenyellow;
border-color: limegreen;
}
`)}
`
}
function element(selector, conditions, stylesheet) {
var generatedStyles = ''
var count = 0
var features = {
minWidth: function(el, number) {
return number <= el.offsetWidth
},
maxWidth: function(el, number) {
return number >= el.offsetWidth
},
minHeight: function(el, number) {
return number <= el.offsetHeight
},
maxHeight: function(el, number) {
return number >= el.offsetHeight
},
minChildren: function(el, number) {
return number <= el.children.length
},
maxChildren: function(el, number) {
return number >= el.children.length
},
minCharacters: function(el, number) {
return number <= ((el.value && el.value.length) || el.textContent.length)
},
maxCharacters: function(el, number) {
return number >= ((el.value && el.value.length) || el.textContent.length)
},
minScrollX: function(el, number) {
return number <= el.scrollLeft
},
maxScrollX: function(el, number) {
return number >= el.scrollLeft
},
minScrollY: function(el, number) {
return number <= el.scrollTop
},
maxScrollY: function(el, number) {
return number >= el.scrollTop
},
minAspectRatio: function(el, number) {
return number <= el.offsetWidth / el.offsetHeight
},
maxAspectRatio: function(el, number) {
return number >= el.offsetWidth / el.offsetHeight
},
orientation: function(el, string) {
switch (string) {
case 'portrait':
return el.offsetWidth < el.offsetHeight
break
case 'square':
return el.offsetWidth == el.offsetHeight
break
case 'landscape':
return el.offsetWidth > el.offsetHeight
break
}
}
}
document.querySelectorAll(selector).forEach(function(tag) {
var results = []
var identifier = (selector
+ Object.keys(conditions)
+ Object.values(conditions)).replace(/\W/g, '')
for (test in conditions) {
results.push(
features[test](tag, conditions[test]) ? true : false
)
}
if (results.indexOf(false) == -1) {
tag.setAttribute('data-' + identifier, count)
generatedStyles += stylesheet.replace(/\$this/g,
'[data-' + identifier + '="' + count + '"]')
count++
} else {
tag.setAttribute('data-' + identifier, '')
}
})
return generatedStyles
}
</script>
<script>
// Drag Handles for Touchscreen Users
if(('ontouchstart' in window)||(navigator.msMaxTouchPoints>0)){
var tag = document.querySelectorAll('[data-drag]')
for(i=0;i<tag.length;i++){
var direction = tag[i].getAttribute('data-drag') || 'both'
tag[i].setAttribute('data-container',i)
spawnNubbin(i,direction)
}
function spawnNubbin(element,direction){
var parent = document.querySelector('[data-container="'+element+'"]'),
pTop = parent.scrollHeight - 20,
pLeft = parent.scrollWidth - 20,
nubbin = document.createElement('div')
nubbin.setAttribute('data-nubbin',element)
parent.style.position = 'relative'
parent.style.overflow = 'inherit'
nubbin.style.position = 'absolute'
nubbin.style.top = pTop+'px'
nubbin.style.left = pLeft+'px'
nubbin.setAttribute('data-max-top',pTop)
nubbin.setAttribute('data-max-left',pLeft)
if (direction == 'horizontal'){
nubbin.innerHTML = '<i class="fa fa-arrows-h"></i>'
}
if (direction == 'vertical'){
nubbin.innerHTML = '<i class="fa fa-arrows-v"></i>'
}
if (direction == 'both'){
nubbin.innerHTML = '<i class="fa fa-arrows"></i>'
}
document.addEventListener('mousedown',grab)
document.addEventListener('touchstart',grab)
document.addEventListener('mousemove',drag)
document.addEventListener('touchmove',drag)
document.addEventListener('mouseup',drop)
document.addEventListener('touchend',drop)
parent.appendChild(nubbin)
}
var grabbed
var startX = startY = oldTop = oldLeft = 0
function grab(e){
if (e.target.getAttribute('data-nubbin')){
e.preventDefault()
grabbed = e.target.getAttribute('data-nubbin')
startX = e.clientX || e.touches[0].clientX
startY = e.clientY || e.touches[0].clientY
oldTop = parseInt(e.target.style.top.split('px')[0]) || 0
oldLeft = parseInt(e.target.style.left.split('px')[0]) || 0
}
}
function drag(e){
if (grabbed){
if (e.target.getAttribute('data-nubbin')){
var nubbin = document.querySelector('[data-nubbin="'+grabbed+'"]'),
parent = e.target.parentNode,
direction = parent.getAttribute('data-drag'),
pTop = parent.scrollHeight,
pLeft = parent.scrollWidth,
newTop = oldTop+parseInt((e.clientY||e.touches[0].clientY)-startY),
newLeft = oldLeft+parseInt((e.clientX||e.touches[0].clientX)-startX),
maxTop = parseInt(nubbin.getAttribute('data-max-top')),
maxLeft = parseInt(nubbin.getAttribute('data-max-left')),
filterTop = newTop>=maxTop?newTop:maxTop,
filterLeft = newLeft>=maxLeft?newLeft:maxLeft
if (direction == 'vertical' || direction == 'both'){
nubbin.style.top = filterTop + 'px'
parent.style.height = newTop>maxTop?newTop+15+'px':maxTop+15+'px'
}
if (direction == 'horizontal' || direction == 'both'){
nubbin.style.left = filterLeft + 'px'
parent.style.width = newLeft>maxLeft?newLeft+15+'px':maxLeft+15+'px'
}
JSinCSS()
}
}
}
function drop(e){
grabbed = undefined
JSinCSS()
}
}
// Apply JS-in-CSS during mouse drags
var resizing = false
window.addEventListener('mousedown', function() {
resizing = true
})
window.addEventListener('mousemove', function() {
if (resizing === true) {
JSinCSS()
}
})
window.addEventListener('mouseup', function() {
resizing = false
JSinCSS()
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment