1

I need to get the height of a div and get notified when its height changes according to data.

I am using getBoundingClientRect() to get the height currently, but I don't get notified of any further changes.

I also tried DOMAttrModified and MutationObserver to detect changes in the data, but both of them are not universally supported in all browsers.

What's the best way to get notifications about changes to an element's height?

Nickolay
  • 31,095
  • 13
  • 107
  • 185

1 Answers1

3

The idea (that seems to originate from a blog post on backalleycoder.com) is that you can use

  • onresize on the element itself in IE <=10.
  • scroll events on a specially crafted <div> appended as a child of the element in most other browsers
  • or onresize on <object style="position: absolute; top: 0; left: 0; height: 100%; width: 100%;"> appended as a child of the element.

There's a number of libraries that implement some or all of these approaches:

Note that older questions here on SO talk about:

  • attrchange in jQuery, DOMAttrModified, etc. - that won't help you with detecting height changes that do not involve changing the height attribute
  • DOMSubtreeModified, MutationObserver - can be used to detect changes in content (which is one of the reasons that can lead to height changes -- the other being layout changes, such as a change to the width)
  • older solutions, including some jQuery plugins that use polling to accomplish this -- that's not a recommended solution, because the page will waste the user's battery even when nothing is resized.

[edit] ResizeObserver will allow to detect this without hacks in newer browsers.

Community
  • 1
  • 1
Nickolay
  • 31,095
  • 13
  • 107
  • 185