Scoped Eval Mixin

This JavaScript function lets you define a CSS selector list, and to output CSS rules with JS interpolation from the context of each element in the document matching the selector.

Syntax

scoped(selector, rule)

Example

Input:

scoped('div', `
  margin: 1em;
  background: lime;
  height: eval(this.offsetWidth / (16/9))px;
`)

Output:

/* Scope: div */
[data-scoped-unique="0"] {
  margin: 1em;
  background: lime;
  height: 144.5625px;
}

Code

function scoped(selector, rule) {

  var tag = document.querySelectorAll(selector)
  var style = ''
  var count = 0

  for (var i=0; i < tag.length; i++) {

  var attr = selector.replace(/\W+/g, '')

    tag[i].setAttribute('data-scoped-' + attr, count)

    var scopedRule = rule.replace(/eval\((.*)\)/g, function(string, match){

      var func = new Function('return ' + match)

      return (func.call(tag[i]) || '')

    })

    style += '\n/* Scope: ' + selector + ' */\n'
             + '[data-scoped-' + attr + '="' + count + '"] {\n'
             + '  ' + scopedRule + '\n'
             + '}\n'
    count++

  }

  return style

}

Techniques Capable