JavaScript: Collapse on 'vanilla' javascript

var Collapse = { init: function(element){ if (!element) return false; // Lets check element target type: class or id if (element.indexOf('.') != -1 ){ var getName = element; var getElement = document.querySelector(getName); } else if ( element.indexOf('#') != -1 ) { var getName = element.replace(/\#/g, ''); var getElement = document.getElementById(getName); } if (!getElement.hasAttribute('data-height')){ getElement.style.display = 'block'; getElement.dataset.height = getElement.offsetHeight + 'px'; getElement.style.height = '0'; } return getElement; }, expand: function(element){ var getContent = Collapse.init(element); setTimeout(function(){ getContent.style.height = getContent.dataset.height; }, 20) }, collapse: function(element){ var getContent = Collapse.init(element); getContent.style.height = '0'; } } // Example: var getButton = document.getElementById('buttonCollapse'); getButton.addEventListener('click', function(){ var self = this; var getTarget = self.getAttribute('data-target'); self.classList.toggle('is-active'); self.classList.contains('is-active') ? Collapse.expand(getTarget) : Collapse.collapse(getTarget) }); // HTML: Markup // <button id="buttonCollapse" data-target=".collapse">Drop</button> // Warning: Didnt add any padding/border on main collapse // This is not collapse and hide this // Use style on '.collapse__inner' ( or something else inner element ) // <div class="collapse" id="collapse"> // <div class="collapse__inner"> // <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum velit placeat, dolorem sequi illo nihil pariatur ab fuga enim aliquam!</p> // <p>Natus, explicabo debitis, doloremque commodi dolores quibusdam, at quod possimus autem vitae accusamus fuga sunt a minus saepe amet id.</p> // <p>Quidem quas quasi rerum officia dolores voluptatum debitis, beatae! Aperiam aliquid doloribus esse dolorem quos ad dignissimos totam, itaque aut.</p> // <p>Consequatur id distinctio, veritatis explicabo sunt fugiat aspernatur quaerat, laborum ipsum totam cum culpa libero, eum provident deserunt. Quae, perferendis.</p> // <p>In recusandae sed eum, temporibus nemo. Exercitationem rerum reprehenderit nulla eaque, unde ducimus maiores impedit tempora cupiditate ipsum? Vitae, quia.</p> // </div> // </div> // CSS: Default style // .collapse { // display: none; // transition: height .35s ease-out; // -webkit-transition: height .35s ease-out; // -moz-transition: height .35s ease-out; // -khtml-transition: height .35s ease-out; // overflow: hidden; // }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.