jsFastHeight
Hopefully replaces force-re-flow problems with CSS class changes
by Nate Armstrong
HTML
<button onClick="grow()">grow</button><br>
<button onClick="shrink()">shrink</button><br>
<div id="test" style="height:0px;"><p>This is a test element</p></div>
<br>currentInt: <span id="currentInt"></span>
<br>targetInt: <span id="targetInt"></span>
<br>difference: <span id="difference"></span>
CSS
#test{
background-color:lightgrey;
display:inline-block;
overflow:hidden;
}
#test p {
padding:200px;
}
JavaScript
grow = function(){
let e = document.getElementById('test');
jsFastHeight(true,e);
}
shrink = function(){
let e = document.getElementById('test');
jsFastHeight(false,e);
}
jsFastHeight = function(grow,e){
let limit = 100;
let speed = 10; // increase to speed up the process
let currentInt = parseInt(e.style.height); // turns current height into an integer
let targetInt = e.scrollHeight | 0; // turns current height into an integer
let difference = 0;
update('currentInt',currentInt);
update('targetInt',targetInt);
update('difference',difference);
if(currentInt > targetInt){
difference = currentInt - targetInt;
} else if (currentInt < targetInt){
difference = targetInt - currentInt;
} else {
return difference;
}
while(difference !== 0){
console.log('while fired' + 'limit = ' + limit);
limit--;
if(difference > speed){
difference = difference - speed;
} else {
difference--;
}
if(grow){ // growing
e.style.height = (targetInt - difference) + "px"
} else { // shrinking
e.style.height = (difference) + "px"
}
if(limit == 0){
break;
}
}
}
function update(updateThis,withThis){
let update = document.getElementById(updateThis);
update.innerHTML = withThis;
console.log(updateThis + " " + withThis);
}