Smooth DIV opener
Simple smooth expanding element with Javascript without any framework
by Vincenzo
HTML
<p>
<button type="button" onclick="Smooth.expand('div')">Open</button>
<button type="button" onclick="Smooth.collapse('div')">Close</button>
</p>
<div id="div">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>
CSS
body { font: 14px sans-serif }
.smooth { transition: height .5s }
div {
width:200px;
background:red;
color:white;
display:none;
overflow: hidden;
}
JavaScript
var Smooth = {
init: function(id) {
var el = document.getElementById(id);
if (!el.hasAttribute('data-height')) {
el.style.display = 'block';
el.dataset.height = el.offsetHeight+"px";
el.className = 'smooth';
el.style.height = 0;
}
return el;
},
expand: function(id) {
var div = Smooth.init(id);
setTimeout(function() { div.style.height = div.dataset.height; }, 20);
},
collapse: function(id) {
var div = Smooth.init(id);
div.style.height = 0;
}
}