zfort-fe
8/29/2017 - 11:25 AM

Vanilla.Accordion

Vanilla.Accordion

(function () {
  var accordions, i;
  
  // Make sure the browser supports what we are about to do.
  if (!document.querySelectorAll || !document.body.classList) return;
  
  // Using a function helps isolate each accordion from the others
  function makeAccordion(accordion) {
    var targets, currentTarget, i;
    
    targets = accordion.querySelectorAll('.accordion > * > h1');
    for(i = 0; i < targets.length; i++) {
      targets[i].addEventListener('click', function () {
        if (currentTarget)
          currentTarget.classList.remove('expanded');
        
        currentTarget = this.parentNode;
        currentTarget.classList.add('expanded');
      }, false);
    }

    accordion.classList.add('js');
  }

  // Find all the accordions to enable
  accordions = document.querySelectorAll('.accordion');
  
  // Array functions don't apply well to NodeLists
  for(i = 0; i < accordions.length; i++) {
    makeAccordion(accordions[i]);
  }
  
})();
<section class="accordion">
  <section>
    <h1>Yesterday</h1>
    <p>I was sick yesterday, so not much happened.</p>
  </section>
  <section>
    <h1>Today</h1>
    <p>I have a bunch of things to do today:</p>
    <ul>
      <li>Grocery shopping</li>
      <li>Stop at the bank</li>
      <li>Dinner and a movie</li>
    </ul>
  </section>
  <section>
    <h1>Road Blocks</h1>
    <p>I'm sick!<p>
  </section>
</section>
.accordion.js > * {
  overflow: hidden;
}

.accordion.js > *:not(.expanded) > *:not(h1) {
  max-height: 0;
  margin-top: 0;
  margin-bottom: 0;
  opacity: 0;
  visibility: hidden;
}

.accordion.js > .expanded > *:not(h1) {
  max-height: 10em;
  opacity: 1;
  visibility: visible;
}

.accordion.js > * > h1 {
  cursor: pointer;
  visibility: visible;
}

.accordion.js > * > *:not(h1) {
  transition: max-height 1s,
    visibility 1s,
    margin 1s,
    opacity 1s;
}