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

              
                
	<div class="o-container">

		<div class="o-box" data-state="my-state" data-state-element="o-box" data-state-scope="o-box" tabindex=0>
			Toggles .my-state on self.
		</div>

	</div>

	<button class="js-add">Add</button>

              
            
!

CSS

              
                body {
  font-family:sans-serif;
  text-align:center;
}

.o-container {
  display:flex;
  justify-content:center;
  flex-wrap:wrap;
}

.o-box {
  display:flex;
  width:200px;
  height:200px;
  background:#dddddd;
  margin:5px;
  padding:10px;
  align-items:center;
  justify-content:center;
  user-select:none;
}

.o-box.my-state {
  background-color:#f76c6c;
}

.o-box.my-state-2 {
  background-color:#8bea7c;
}

.o-box.my-state.my-state-2 {
  background-color:#C6A573;
}

.o-box.my-state-3 {
  background-color:#5bc0ff;
}

button {
  margin:30px auto;
  font-size:24px;
}

.u-center {
  margin-left:auto;
  margin-right:auto;
}
              
            
!

JS

              
                (function(){
  // CLOSEST PARENT HELPER FUNCTION
  //----------------------------------------------
  var closestParent = function(child, match) {
    if (!child || child == document) {
      return null;
    }
    if (child.classList.contains(match) || child.nodeName.toLowerCase() == match) {
      return child;
    }
    else {
      return closestParent(child.parentNode, match);
    }
  },

  // REUSABLE FUNCTION
  //----------------------------------------------

  // Change function
  processChange = function(elem){
    // Grab classes list and convert to array
    var dataState = elem.getAttribute('data-state');
    dataState = dataState.split(", ");

    // Grab linked elements list and convert to array
    var dataStateElement = elem.getAttribute('data-state-element');
    dataStateElement = dataStateElement.split(", ");

    // Grab data-state-behaviour list if present and convert to array
    if(elem.getAttribute("data-state-behaviour")) {
      var dataStateBehaviour = elem.getAttribute("data-state-behaviour");
      dataStateBehaviour = dataStateBehaviour.split(", ");
    }

    // Grab data-scope list if present and convert to array
    if(elem.getAttribute("data-state-scope")) {
      var dataStateScope = elem.getAttribute("data-state-scope");
      dataStateScope = dataStateScope.split(", ");
    }

    // Loop through all our dataStateElement items
    for(var b = 0; b < dataStateElement.length; b++) {
      // Grab elem references, apply scope if found
      if(dataStateScope && dataStateScope[b] !== "false") {
        // Grab parent
        var elemParent = closestParent(elem, dataStateScope[b]),

        // Grab all matching child elements of parent
        elemRef = elemParent.querySelectorAll("." + dataStateElement[b]);

        // Convert to array
        elemRef = Array.prototype.slice.call(elemRef);

        // Add parent if it matches the data-state-element and fits within scope
        if(dataStateScope[b] === dataStateElement[b] && elemParent.classList.contains(dataStateElement[b])) {
          elemRef.unshift(elemParent);
        }
      }
      else {
        var elemRef = document.querySelectorAll("." + dataStateElement[b]);
      }
      // Grab state we will add
      var elemState = dataState[b];
      // Grab behaviour if any exists
      if(dataStateBehaviour) {
        var elemBehaviour = dataStateBehaviour[b];
      }
      // Cycle through target elements
      for(var c = 0; c < elemRef.length; c++) {
          // Find out if we're manipulating aria-attributes or classes
          var toggleAttr;
          if(elemRef[c].getAttribute(elemState)) {
              toggleAttr = true;
          }
          else {
              toggleAttr = false;
          }
          if(elemBehaviour === "add") {
              if(toggleAttr) {
                  elemRef[c].setAttribute(elemState, true);
              }
              else {
                  elemRef[c].classList.add(elemState);
              }
          }
          else if(elemBehaviour === "remove") {
              if(toggleAttr) {
                  elemRef[c].setAttribute(elemState, false);
              }
              else {
                  elemRef[c].classList.remove(elemState);
              }
          }
          else {
              if(toggleAttr) {
                  if(elemRef[c].getAttribute(elemState) === "true") {
                      elemRef[c].setAttribute(elemState, false);
                  }
                  else {
                      elemRef[c].setAttribute(elemState, true);
                  }
              }
              else {
                  elemRef[c].classList.toggle(elemState);
              }
          }
      }
    }
  },
  // Init functiom
  initDataState = function(elem){
    // Add event listeners to each one
    elem.addEventListener("click", function(e){
      // Prevent default action of element
      e.preventDefault();
      // Run state function
      processChange(this);
    });    
    // Add keyboard event for enter key to mimic anchor functionality
    elem.addEventListener("keypress", function(e){
        if(e.which === 13) {
            // Prevent default action of element
            e.preventDefault();
            // Run state function
            processChange(this);
        }
    });
  }

  // Run when DOM has finished loading
  document.addEventListener("DOMContentLoaded", function() {

    // Grab all elements with required attributes
    var elems = document.querySelectorAll("[data-state][data-state-element]");

    // Loop through if any are found
    for(var a = 0; a < elems.length; a++){
      initDataState(elems[a]);
    }

    // Setup mutation observer to track changes for matching elements added after initial DOM render
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var d = 0; d < mutation.addedNodes.length; d++) {
                // Check if we're dealing with an element node
                if(typeof mutation.addedNodes[d].getAttribute === 'function') {
                    if(mutation.addedNodes[d].getAttribute("data-state")) {
                         initDataState(mutation.addedNodes[d]);
                    }
                }
            }
        });  
    });

    // Define type of change our observer will watch out for
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
  });

  var button = document.querySelector(".js-add"),
      container = document.querySelector(".o-container");
  button.addEventListener("click", function(){
    container.insertAdjacentHTML('beforeend', '<div class="o-box" data-state="my-state" data-state-element="o-box" data-state-scope="o-box" tabindex=0>New Box<br>Toggles .my-state on self.</div>');
  });
})();
              
            
!
999px

Console