this is kind of javascript/browser theoretical question. My colleague and I are trying to write jQuery slideUp method in vanilla JS. The important part of the function body reads:
// initial height needs to be set
if (!element.style.height) {
element.style.height = `${element.scrollHeight}px`;
}
element.style.overflowY = 'hidden';
element.style.transition = `height ${duration / 1000}s ease-out`;
element.style.height = '0';
This does not work, it slides up without animation. It is like the code in if statement was not executed, but it is in our scenario. Reaplacing the last line with setTimeout works, of course:
setTimeout(function() {
element.style.height = '0';
}, 50);
The question is, why does the first case not work? I beilieve it is becouse the value of height is not really changed, but "rewritten" instead, so to speak. Something like height = '250px' = '0px'
, almost, at least, there is some tiny delay though.So is it, that the browser does not register the delay of change in height? Or is the value simply rewritten immediatelly, so it is like the initial height was not set at all? Is it therefore necessary to use setTimout(), or can one avoid it?
My colleague claims that when he set the timeout function to 10ms, it did not work. But I think that was a coincidence, it worked for me even with 0ms (as it should, if I understand asynchronous calling correctly). Thank you for any explanation.