Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Calculating Width and Height After All Active CSS Transitions Complete

Is it possible to calculate the size of an element after an animation has complete using jQuery? My simplified example is:

<style>
  .brick
  {
    transition: all 0.4s ease-in-out;
  }
  .large
  {
    width: 400px;
    height: 400px;
  }
  .small
  {
    width: 200px;
    height: 200px;
  }
</style>

<script>
  $('.brick').removeClass('small').addClass('large');
  $('.brick').height(); // returns 200px but desired 400px
  $('.brick').width();  // returns 200px but desired 400px
</script>

I can't wait until after the animation completes to get the sizes and I can't hardcode any of the sizes in the JS. Any ideas?

Edit: Typo on sizes for small and large

like image 450
Kevin Sylvestre Avatar asked Jun 12 '13 19:06

Kevin Sylvestre


2 Answers

You could just create an element with the same class and no transition, and get the dimensions of that element, as that would be the same as when the transition ends on the existing element :

var brick = $('<div />', {
                          'class':'brick large', 
                           style :'transition:none; left: -9999px;'
                         }
            ).appendTo('body');

var w = brick.height()
var h = brick.width();

brick.remove();

FIDDLE

like image 192
adeneo Avatar answered Oct 09 '22 09:10

adeneo


You totally can, just listen to the "transitionend" event on the element. Note the name of the event is different depending on browser vendors. For a complete list look here.

UPDATE:
Okay so based on your comment I assume you want the resulted sizes right after you initiated the animation. Things to keep in mind tho is for the javascript to fetch the size of an element, the element has to already be that size.

I can think of 2 approaches as for now:

  1. Instantly apply the size change on the child container, but animate the parent container. You will know the resulted size by looking at the size of the child container. You can have overflow:hidden on the parent container to void content overflowing in process of the animation. Notice that "instantly apply size change' doesn't mean you can't apply animations at all, you can still apply animations only if they do not interfere with the size, for example, fadeIn.
  2. Construct a dummy element that's identical to the one you are interested in, remove CSS3 transitions on that element and apply the class changes, then grab the size of the dummy element.
like image 27
Xavier_Ex Avatar answered Oct 09 '22 10:10

Xavier_Ex