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

              
                <button id="menu-button" class="js-menu-button" data-state="aria-expanded" data-state-element="js-menu-button" aria-expanded="false">Toggle Menu</button>

<nav class="c-menu" data-state="aria-expanded" data-state-element="js-menu-button" data-state-behaviour="remove" data-state-swipe="right, true" aria-hidden="true" aria-labelledby="menu-button">
  <div class="c-menu__inner">
     <ul>
       <li><a class="c-menu__link" href="#">Link</a></li>
       <li><a class="c-menu__link" href="#">Link</a></li>
       <li><a class="c-menu__link" href="#">Link</a></li>
    </ul>
  </div>
  <div class="c-menu__close" data-state="aria-expanded" data-state-element="js-menu-button" data-state-behaviour="remove" tabindex="0">[X] Close</div>
</nav>


              
            
!

CSS

              
                body {
  margin:0;
  overflow-x:hidden;
  font-family:sans-serif;
}

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

.c-menu {
  background:#dddddd;
  width:400px;
  height:100%;
  top:0;
  right:-500px;
  position:absolute;
  transition:right 0.5s;
}

.c-menu__close {
  position:absolute;
  right:10px;
  top:10px;
  cursor:pointer;
}

.c-menu__inner {
  padding:10px;
}

.c-menu[aria-hidden="true"] {
  visibility:hidden;
}

.js-menu-button[aria-expanded="true"] ~ .c-menu {
  right:0;
  visibility:visible;
}
              
            
!

JS

              
                (function(){
  // SWIPE DETECT HELPER
  //----------------------------------------------
  var swipeDetect = function(el, callback){ 
    var touchsurface = el,
    swipedir,
    startX,
    startY,
    dist,
    distX,
    distY,
    threshold = 100,
    restraint = 100,
    allowedTime = 300,
    elapsedTime,
    startTime,
    eventObj,
    handleswipe = callback || function(swipedir, eventObj){}

    touchsurface.addEventListener('touchstart', function(e){
      var touchobj = e.changedTouches[0]
      swipedir = 'none'
      dist = 0
      startX = touchobj.pageX
      startY = touchobj.pageY
      startTime = new Date().getTime()
      eventObj = e;
    }, false)

    touchsurface.addEventListener('touchend', function(e){
      var touchobj = e.changedTouches[0]
      distX = touchobj.pageX - startX
      distY = touchobj.pageY - startY
      elapsedTime = new Date().getTime() - startTime
      if (elapsedTime <= allowedTime){
        if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint){
          swipedir = (distX < 0)? 'left' : 'right'
        }
        else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint){
          swipedir = (distY < 0)? 'up' : 'down'
        }
      }
      handleswipe(swipedir, eventObj)
    }, false)
  }

  // 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 function
  initDataState = function(elem){
      // Detect data-swipe attribute before we do anything, as its optional
      // If not present, assign click event like before
      if(elem.getAttribute("data-state-swipe")){
          // Grab swipe specific data from data-state-swipe
          var elemSwipe = elem.getAttribute("data-state-swipe"),
            elemSwipe = elemSwipe.split(", "),
            direction = elemSwipe[0],
            elemSwipeBool = elemSwipe[1],
            currentElem = elem;

      // If the behaviour flag is set to "false", or not set at all, then assign our click event
          if(elemSwipeBool === "false" || !elemSwipeBool) {
              // Assign click event
              elem.addEventListener("click", function(e){
                  // Prevent default action of element
                  e.preventDefault(); 
                  // Run state function
                  processChange(this);
              });
          }
          // Use our swipeDetect helper function to determine if the swipe direction matches our desired direction
          swipeDetect(elem, function(swipedir){
              if(swipedir === direction) {
                  // Run state function
                  processChange(currentElem);
              }
          })
      }
      else {
          // Assign click event
          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
    });
  });

  /*
  Additional code to:

  [1] Make aria-hidden true on completion of transition so we can correctly trigger visibility:hidden and stop unintentional user focus on the menu
  [2] Make first nav link in focus
  */

  var menu = document.querySelector(".c-menu"),
      button = document.querySelector(".js-menu-button"),
      navLink = menu.querySelector(".c-menu__link")
  menu.addEventListener("transitionend", function(e){
    if(button.getAttribute("aria-expanded") === "true") {
      this.setAttribute("aria-hidden", "false");
      navLink.focus();
    }
    else {
      this.setAttribute("aria-hidden", "true");
    }
  });
})();
              
            
!
999px

Console