jQuery: lower element height from top to bottom

Lowering the height of an element with the animate() method can be misleading. In fact, even the element's container will shrink its height following the animation's flow. That's not what we want. We want to lower the height from top to bottom with a particular shrinking effect. Here's the solution.

Given this markup:

<div id="container">
 <div id="test"></div>

With the following styles:

#container {
 margin: 2em auto;
 width: 500px;
 border-bottom: 1em solid #333;

#test {
 width: 200px;
 height: 200px;
 background: #d34545;
 cursor: pointer;

span.line {
 width: 200px;
 height: 1px;
 display: block;
 background: #fff;

we can lower the height of our element by simply inserting multiple line elements using a JavaScript timer:

$('#test').click(function() {
    var $div = $(this);
    var height = $div.height();
    var index = 0;
    var timer = setInterval(function() {
      if(index == parseInt(height / 2)) {
      $('<span class="line"/>').appendTo($div);
    }, 10);

Timer's limit is given by half the height of our element. You can see the demo below.


Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “jQuery: lower element height from top to bottom”

  1. It would be maybe better to append just ONE span and then changing the height of that particular span? This way it would be easier to use easing functions, and to revert the effect, and it wouldn't clutter the markup so much

Leave a Reply

Note: Only a member of this blog may post a comment.