One common situation in web developing is that you want to expand and collapse an element (maybe a DIV) with a smooth animation. It’s a common request because having a smooth animation helps the user to follow what happens on the page without being disorientated by fast changes.
You can easily obtain a smooth animation using CSS transition in all modern browsers, so there’s not much to do except a simple CSS rule. But CSS animations work only if you know exactly the initial and the final value of your property and if you have a DIV with some text inside you can’t now the exact final height.
In my example the expand function takes a string and pass it to the init function, the most important function in my three function singleton object 🙂
The collpase function does almost the same, but sets the new height to zero. So if this function is called before expand everything will work and we don’t need the setTimeout trick.
Every following click action on the buttons will simply change the DIV’s height value. In fact the setTimout in the expand function is unnecessary at this point, but keeping it will not change much.
If the DIV’s height changes between one expansion and the next one we will have a wrong value stored, so you have to update the value whenever necessary.