Posted by: Joe Devietti on: November 18, 2010
I recently decided to add paper abstracts to my academic website, to allow people to get a quick overview of a paper without downloading the whole thing. I wanted these abstracts to be hidden at first, and then revealed by clicking on a link. The perfect excuse to dabble in a bit of Javascript, and whip something up in an hour or two, right?
With Google-given example code I was indeed able to get something basic working pretty quickly that made the entire abstract either visible or not, by twiddling the display CSS property. Then I started thinking: what would it take to have the abstract appear with a “slide in” animation, instead of just suddenly becoming visible?
Well, at least I had good intentions to start.
After many hours of fumbling, I got something pretty decent working with jQuery. The only issue was that the animation was a bit “jumpy” at the end. This weirdness persisted across all the browsers I tried (Firefox and Chrome on Linux, and Firefox and IE on Windows). Many of the examples I found on the internet were for sliding in fixed-height content, but I couldn’t specify the height of each abstract in advance, since they were all of different lengths (i.e., word counts).
My desperate mind turned to thoughts of hacking at the jQuery code, and then, slightly more plausibly, rendering the text invisibly in the background, reading its height via Javascript and recording it in CSS, and then making the text display: none; again. I was setting in on coding this solution (which I still think would have been a lot of fun, despite its patent horribleness) when I discovered this comment on the jQuery documentation page for slideToggle(). Turns out I just needed to set the width of the content (which was fixed for my page), and that would add enough constraints to the layout to allow browsers to render the animation smoothly.
It was all of a 1-line CSS fix in the end.
p.s. You can see the “jumpiness” that results when the div being animated doesn’t have a width constraint in this example I put together. There’s also a demo of the fixed code. Curiously, an explicit width on some parent div (which I’d had all along) is not sufficient to force the smooth animation of a child; the child itself needs a width (or height). This code uses jQuery 1.4.3.
December 17, 2011 at 3:04 am
aww thanks a lot. you really helped me
I used it before and was working properly and this time seems i missed width for the element and couldn’t fix it before reading that post. well done. thanks