Last active
December 22, 2015 11:48
-
-
Save patik/6467961 to your computer and use it in GitHub Desktop.
Transition height/width to `auto` by defining the transition in CSS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.expandable { | |
transition-property: none; | |
transition-duration: .5s; | |
transition-timing-function: ease-in-out; | |
} | |
/* Vary the transition with different classes */ | |
.expandable.molasses { | |
transition-duration: 3s; | |
} | |
.expandable.robotic { | |
transition-timing-function: linear; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function expandWidth(element) { | |
var prevWidth = element.style.width, | |
endWidth; | |
// Get the element's true 'auto' width | |
element.style.width = 'auto'; | |
endWidth = getComputedStyle(element).width; | |
element.style.width = prevWidth; | |
element.offsetWidth; // Force repaint | |
// Get transition values from the CSS | |
element.style.transitionProperty = 'width'; | |
element.style.transitionDuration = getComputedStyle(element).transitionDuration; | |
element.style.transitionTimingFunction = getComputedStyle(element).transitionTimingFunction; | |
element.style.width = endWidth; | |
element.addEventListener('transitionend', function transitionEnd(event) { | |
if (event.propertyName === 'width') { | |
element.style.transition = ''; | |
element.style.width = 'auto'; | |
element.removeEventListener('transitionend', transitionEnd, false); | |
} | |
}, false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my fork of Nikita Vasilyev's method. More about it in this blog post.