Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active April 10, 2018 06:29
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Container Queries Mixin: Stylesheet version (using $this as a keyword for matching tags)
function containerQuery(selector, test, stylesheet) {
var tag = document.querySelectorAll(selector)
var style = ''
var count = 0
for (var i=0; i<tag.length; i++) {
var attr = (selector+test).replace(/\W+/g, '')
if (test(tag[i])) {
var css = stylesheet.replace(/:self|\$this/g, '[data-' + attr + '="' + count + '"]')
tag[i].setAttribute('data-' + attr, count)
style += css
count++
} else {
tag[i].setAttribute('data-' + attr, '')
}
}
return style
}
let containerQuery = (selector, test, stylesheet) => {
let style = ''
let count = 0
document.querySelectorAll(selector).forEach(tag => {
const attr = (selector+test).replace(/\W+/g, '')
if (test(tag)) {
const css = stylesheet.replace(/:self|\$this/g, `[data-${attr}="${count}"]`)
tag.setAttribute(`data-${attr}`, count)
style += css
count++
} else {
tag.setAttribute(`data-${attr}`, '')
}
})
return style
}
@VPenkov
Copy link

VPenkov commented Nov 13, 2017

The ES5 version is a bit incorrect. Template literals are not an ES5 feature so the backticks need to go away.
In the ES6 version, I believe you don't ever change attr and css in the forEach call so they should be consts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment