All Projects → m3g4p0p → get-height

m3g4p0p / get-height

Licence: other
Get the "potential" height of a hidden DOM element

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

get-height

Get the "potential" height of a hidden DOM element, that is, an element that has set display: none or hidden=true.

Mkay

This can be useful if you want to apply a CSS driven slide-down animation to a previously hidden element, as you can't have a transition from display: none to height: auto (obviously). For example. It was the motivation for me at any rate...

.hidden {
  display: none;
}

.about-to-slide-down {
  display: block;
  height: 0;
  overflow: hidden;
  transition: height .2s ease;
}
import { getHeight } from 'get-height'

// Then at some point...
const element = document.querySelector('.hidden')

getHeight(element).then(height => {
  element.classList.add('about-to-slide-down')

  window.requestAnimationFrame(() => {
    element.style.height = height + 'px'
  })

  element.addEventListener('transitionend', () => {
    element.style.height = 'auto'
  }, { once: true })
})

Installation

yarn add get-height

API

getHeight(element: HTMLElement, includeMargins: boolean = true): Promise<number>

But why asynchronous?

In order to determine the height the element would have on the page, the DOM has to be temporarily rearranged a bit. This is getting scheduled in animation frames to avoid layout thrashing and the performance issues of jQuery's outerHeight() method (also, the element will not be visible at any point).

Limitations danger

It may not work reliably.

License

MIT@m3g4p0p

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].