Final Transition Dimensions

by the_lee_man

HTML

<div id="resizeBox" class="variableBox">WELL, PRINCE, Genoa and Lucca are now no more than private estates of the Bonaparte family. No, I warn you, that if you do not tell me we are at war, if you again allow yourself to palliate all the infamies and atrocities of this Antichrist (upon my word, I believe he is), I don't know you in future, you are no longer my friend, no longer my faithful slave, as you say. There, how do you do, how do you do? I see I'm scaring you, sit down and talk to me."</div>

CSS

.variableBox {
  outline: 1px solid red;
  width: 200px;
  transition: width 2s ease, height 2s ease;
}

JavaScript

function resize(element, endingWidth) {
  // First, save any set transitions for later.
  var transitions = window.getComputedStyle(element).transition;
  // Now, disable any transitions so that our calculations will work properly.
  element.style.transition = 'none';
  // Get our current width.
  var startingWidth = element.offsetWidth + 'px';

  // Set a new width.
  element.style.width = endingWidth;
  // And get the element height. Because there are no transitions set, this will be the same height as at the end of any transitions.
  var endingHeight = element.offsetHeight;

  /*
				 * Now do whatever calculations we want with the ending height.
				 */
  alert(endingHeight);

  // Set the element's width back to when we started, so we have a start point for our transition.
  element.style.width = startingWidth;
  // Force the browser to recalculate the element's dimensions. This seemingly pointless call is absolutely critical for the transition to work.
  element.offsetWidth;

  // Now, we can set our desired transitions and the ending width again, and we're away.
  element.style.transition = transitions;
  element.style.width = endingWidth;

}
			
			// Ensure we only resize once we've been rendered.
			window.addEventListener('load', function() {	
				resize(document.getElementById('resizeBox'), '400px');
			});