Quick paragraph accordion example

by Julien Etienne

HTML

<section>
  <p>The path of the righteous man is beset on all sides</p>
  <p>by the inequities of the selfish and the tyranny of evil men</p>
  <p>And I will strike down upon thee with great </p>
  <p>vengeance and furious anger those who would attempt</p>
  <p>to poison and destroy my brothers</p>
</section>

CSS

p {
  cursor: pointer;
  height: 0;
  overflow: hidden;
  background: yellowgreen;
  -webkit-transition: all 0.5s ease;
  -moz-transition: all 0.5s ease;
  -o-transition: all 0.5s ease;
  transition: all 0.5s ease;
}

p:first-child {
  height: auto;
}

JavaScript

var section = document.getElementsByTagName('section')[0];
    var sectionArray = [].slice.call(section.children);

    section.addEventListener('click', showHide, true);

    function showHide(e) {
      var target = e.target;
      var indexOfSection = sectionArray.indexOf(target);
      var elementToToggleHeight;
      // If element is a paragraph
      if (target.tagName === 'P') {
        var elementToToggle = section.children[indexOfSection + 1];

        if(indexOfSection + 1 < sectionArray.length){
          elementToToggleHeight = parseInt(window.getComputedStyle(elementToToggle, null).getPropertyValue("height"),10);
          }

        if (elementToToggleHeight) {
          // Function to close all except current and first
          sectionArray.forEach(function(paragraph){
            if(paragraph !== target && paragraph !== sectionArray[0]){
            paragraph.style.height = 0;
            }
          });

        } else {
          if(elementToToggle)
          elementToToggle.style.height = '1em';
        }
      }
    }