Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Last active April 10, 2018 06:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/fc42b334beaafc75a271b1ef7c8e33ee to your computer and use it in GitHub Desktop.
Save tomhodgins/fc42b334beaafc75a271b1ef7c8e33ee to your computer and use it in GitHub Desktop.
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