Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>CSS attr() polyfill</h1>
<p> This polyfill makes it possible to use <code>attr()</code> like it is defined in the <a href="http://www.w3.org/TR/2013/CR-css3-values-20130730/#attr">spec</a>.
You can drag the sliders to manipulate the data-attributes. <s>In Google Chrome you will get instand feedback.</s> Firefox will wait till the user interaction is finished, than the MutationObserver kicks in.</p>

<h2>Demos</h2>

<h3>Simple Demo</h3>
<div class="demo1" id="js-demo1" data-width="100" data-height="100"></div>

<pre class="demoContainer container-html ">
  &lt;div class="demo1" data-width="<input class="slider js-slider" data-target="js-demo1" data-attr="data-width" type="range" min="50" max="200" value="50"/>" data-height="<input class="slider js-slider" data-target="js-demo1" data-attr="data-height" type="range" min="50" max="200" value="50"/>"&gt
</pre>
<pre>
  <style class="demoContainer container-styles js-demo1">
    .demo1{
      width:attr(data-width px);
      height:attr(data-height px);  
    
      display:block;
      background:green;  
    }
  </style>
</pre>

<h3>Advanced Demo</h3>

<div class="demo2" id="js-demo2" data-bg-rotation="0"></div>

<pre class="demoContainer container-html">
  &lt;div class="bar" data-bg-rotation="<input class="slider js-slider" data-target="js-demo2" data-attr="data-bg-rotation" type="range" min="0" max="360" value="50"/>">
</pre>

<pre>  
<style class="demoContainer container-styles js-demo2">
    .demo2{    
      background:linear-gradient(attr(data-bg-rotation deg), blue, green);
      background:-webkit-linear-gradient(attr(data-bg-rotation deg), blue, green);
  
      display:block;
      width:100px;
      height:100px;
    }
  </style>
</pre>

  
<h3 id="calc">Combine with native calc()</h3>
  
  <div class="demo3" id="js-demo3" data-addition="50"></div>

<pre class="demoContainer container-html">
  &lt;div class="bar" data-addition="<input class="slider js-slider" data-target="js-demo3" data-attr="data-addition" type="range" min="0" max="100" value="50"/>">
</pre>

<pre>  
<style class="demoContainer container-styles js-demo3">
    .demo3{    
      height:50px;
      width:calc( 10px + attr(data-addition px));
      background:green;
      display:block;
    }
  </style>
<pre>
              
            
!

CSS

              
                

.demoContainer{
  position:relative;
  display:block;  
  border-radius:5px;
}
.demoContainer:before{
  position:absolute;
  top:5px; right:5px;
  
  font-family: sans-serif;
  font-size:12px;
}

.container-html{
  border:1px solid darkblue;
  background:lightblue;
  padding:2em 0 2em 0;
}
.container-html:before{
  content:'HTML';
}

.container-styles{
  border:1px solid darkgreen;
  background:lightgreen;
}
.container-styles:before{
  content:'CSS';
}


body{
  font-family:sans-serif;  
}

.slider{
  display:inline-block;
  vertical-align:middle;
  width:50px;
}
              
            
!

JS

              
                /*! CSS3 attr() Polyfill - v0.0.2 - 2013-08-16
 * 
 * Copyright (c) 2013 Fabrice Weinberg
 */
;(function (exports){

function PropertyValueParser(){ }

PropertyValueParser.prototype = {
  /**
   * This function will convert CSS Propertys like:
   * "border-raidus" to "borderRadius" or
   * "-webkit-transform" to "webkitTransform"
   */
  hyphenToCamelCase : function (property) {
      // Is there a hyphen?
      if (property.indexOf('-') === -1) return property;
      // Take care of the - for vendor prefixes
      if (property.charAt(0) === '-') property = property.substr(1);

      var spl = property.split('-'),
          result = '',
          length = spl.length;
      for (var i = 1; i < length; i++) {
          var w = spl[i];
          // First letter in uppercase rest in lowercase
          result += w[0].toUpperCase() + w.substr(1).toLowerCase();
      }
      return spl[0].toLowerCase()+result;
  },

  parseParam : function(params){
    var spaceStart = params.indexOf(' '),
        commaStart = params.indexOf(','),
        attrName   = '',
        unit       = '',
        fallback   = '';

    if (spaceStart !== -1) {
        attrName = params.substr(0, spaceStart).trim();
        if (commaStart !== -1) {
            unit = params.substr(spaceStart + 1, commaStart - (spaceStart + 1)).trim();
        } else {
            unit = params.substr(spaceStart + 1).trim();
        }
    }
    if (commaStart !== -1) {
        fallback = params.substr(commaStart + 1).trim();
    }
    // If attr is not yet set params must be the attrName;
    if (attrName === ''){
      attrName = params;
    }
    return [attrName, unit, fallback];
  },

  parse : function(property, value){
    if (!property  || !value) return null;

    var result = [],
        attr   = [],
        last   = 0,
        i      = 0,
        funcStart,
        funcEnd;

    // Simple check to see if there is a valid function statement.
    if ( value.indexOf('(') !== -1 && value.split("(").length === value.split(")").length) {
      // Search for the attr( function
      while ((i = value.indexOf("attr(", last)) !== -1) {

          funcStart = i + 5; // Add 5 for attr(
          funcEnd   = value.indexOf(")", funcStart);

          // Add letters between each attr() occurence
          if (i - last !== 0)
            result.push('"' + value.substr(last, i - last) + '"');

          // Parse attr() function for paramater
          var param = this.parseParam(value.substr(funcStart, funcEnd - funcStart));
          if (param[0] === '') return null; // Empty attr() function

          // Translate it to Javascript
          result.push('(n.hasAttribute("' + param[0] + '") ? (n.getAttribute("' + param[0] + '") + "' + param[1] + '") : "' + param[2] + '" + "' + param[1] + '")');
          // Add the Attribute to the attrCache
          attr.push(param[0]);

          last = ++funcEnd;
      }
      if (last > 0){
        // Add the remaining string after the last attr() function
        result.push('"' + value.substr(last) + '"');

        return {
            // Build new JavaScript Function
            func     : new Function('n', 'return ' + result.join('+')),
            attr     : attr,
            cssProp  : this.hyphenToCamelCase(property)
        };
      }
    }
    return null;
  }
};

var CSSParser = (function(propertyValueParser){
  var push     = [].push,
      cssRule  = /\s*(.*?)\s*{([^}]*)}/g,
      cssParse = /\s*(.*?)\s*:\s*([^;]*?);/g;

  function CSSParser() { }

  CSSParser.prototype = {

    parse : function (css) {
      if (css === undefined) return {};
      css = css.replace(/(?:\r|\n)/g, '').replace(/\/\*.+?\*\//g, '').toLowerCase();
      var ruleMatch, propMatch, cssExtendedFunction = {};
      while ((ruleMatch = cssRule.exec(css)) !== null) {
        var selector = ruleMatch[1],
            body     = ruleMatch[2];

        while ((propMatch = cssParse.exec(body)) !== null) {
          var parsedCssValue = propertyValueParser.parse(propMatch[1], propMatch[2]);
          // Ignore 'Content' css property.
          if (parsedCssValue !== null && parsedCssValue.cssProp !== 'content') {
            var selectorData = cssExtendedFunction[selector] || {
                                                                  attr: {},
                                                                  filter: []
                                                                };
            // Add dataAttr to filter
            push.apply(selectorData.filter, parsedCssValue.attr);
            // Add cssFunc to each dataAttr in selectorData;
            parsedCssValue.attr.forEach(function (i) {
              selectorData.attr[i] = (selectorData.attr[i] || []);
              selectorData.attr[i].push(parsedCssValue);
            });

            cssExtendedFunction[selector] = selectorData;
          }
        }
      }
      return cssExtendedFunction;
    }
  };

  return CSSParser;
})(new PropertyValueParser());

function StyleGenerator(doc){
  this.doc = doc;
}

StyleGenerator.prototype = {

  resolveFuncList : function (node, styles, cssPropValueList) {
    var result, attrFunc;
    for (var i = 0; i < cssPropValueList.length; i++) {
      var value = cssPropValueList[i];
      styles[value.cssProp] = value.func(node);
    }
  },

  generate : function (ast) {
    var styleMap = [];
    for (var selector in ast) {
      var nodeList     = this.doc.querySelectorAll(selector),
          selectorData = ast[selector];
      for (var i = 0; i < nodeList.length; i++) {
        var node    = nodeList[i],
            styles  = {},
            styleMapForNode = {
                node  : node,
                styles: styles
            };

        for (var dataAttr in selectorData.attr) {
            var cssPropValueList = selectorData.attr[dataAttr];
            this.resolveFuncList(node, styles, cssPropValueList);
        }

        styleMap.push(styleMapForNode);
      }
    }
    return styleMap;
  },

  apply : function (styleMap) {
      // Write styles to node.
      for (var i = 0; i < styleMap.length; i++) {
          var styleForNode = styleMap[i],
              node = styleForNode.node,
              styles = styleForNode.styles;

          for (var prop in styles) {
              node.style[prop] = styles[prop];
          }
      }
  }
};

function NodeObserver(observerList, mutationObserver, styleGenerator, doc){
  this.observerList     = observerList;
  this.mutationObserver = mutationObserver;
  this.styleGenerator   = styleGenerator;
  this.doc              = doc;
}

NodeObserver.prototype = {

  remove : function () {
      this.observerList.forEach(function (observer) {
          observer.disconnect();
      });
  },

  add : function (node, attr, filter) {
      var styleGenerator =  this.styleGenerator;
      var observer = new this.mutationObserver(function (mutationList) {
          var styles = {},
          styleMap = [{
              node: node,
              styles: styles
          }];
          for (var i = 0; i < mutationList.length; i++) {
              var mutation = mutationList[i],
                  attrName = mutation.attributeName;
              if (node.getAttribute(attrName) !== mutation.oldValue) {
                  styleGenerator.resolveFuncList(node, styles, attr[attrName]);
              }
          }
          styleGenerator.apply(styleMap);
      });
      observer.observe(node, {
          attributes: true,
          attributeOldValue: true,
          attributeFilter: filter
      });

      return observer;
  },

  attach : function (ast) {
      for (var selector in ast) {
          var nodeList = this.doc.querySelectorAll(selector),
              selectorData = ast[selector];
          for (var i = 0; i < nodeList.length; i++) {
              var node = nodeList[i];
              this.observerList.push(this.add(node, selectorData.attr, selectorData.filter));
          }
      }
  }
};
exports.cssattr = (function(cssParser, styleGenerator, nodeObserver){
  return {
    parse: function (css) {
        this.cssAst = cssParser.parse(css);
        return this;
    },
    show: function () {
        styleGenerator.apply(styleGenerator.generate(this.cssAst));
        return this;
    },
    observe: function () {
        nodeObserver.attach(this.cssAst);
        return this;
    },
    unobserve: function () {
        nodeObserver.remove();
        return this;
    }
  };

})( new CSSParser(),
    new StyleGenerator(document),
    new NodeObserver([], MutationObserver ||  WebKitMutationObserver, 
    new StyleGenerator(document), document) );
})(window);
 
// Get all demo styles
var styleNode = document.querySelectorAll('.container-styles'),
    css = '';
for (var i = 0; i < styleNode.length; i++) {
    css += styleNode[i].innerHTML;
}

// Parse the CSS, show the result and observe for changes;
cssattr.parse(css).show().observe();

var sliderList = document.querySelectorAll('.js-slider');

for (var i=0;i<sliderList.length;i++){
  var slider = sliderList[i],
      target = document.querySelector('#'+slider.getAttribute('data-target')),
      attrName = slider.getAttribute('data-attr');
  
  slider.onchange = (function(attrName, target){
    return function (){
      target.setAttribute(attrName, this.value);
    }
  })(attrName, target);
}

              
            
!
999px

Console