sdecima / javascript-detect-element-resize

A Cross-Browser, Event-based, Element Resize Detection
MIT License
880 stars 150 forks source link

javascript-detect-element-resize

A Cross-Browser, Event-based, Element Resize Detection.

In short, this implementation does NOT use an internal timer to detect size changes (as most implementations I found do). It uses scroll events on most browsers, and the onresize event on IE10 and below.

The method used not only detects javascript generated resize changes but also changes made from CSS pseudo classes e.g. :hover, CSS animations, etc.

About the libraries

I was searching for a library that allowed me to detect when an DOM element changes size, and all solutions I found had two problems:

  1. only available as jQuery libraries (so no standalone Javascript)
  2. all had terrible performance (because all of them use timers to intermittently poll the size of the elements to detect a change).

Then I came across this great post on Back Alley Coder about using overflow and underflow events scroll events to do event-based element resize detection; and it works great without consuming resources at all (just like any other browser originated event).

The libraries on this repository are just a ready-to-use implementation of the above, one pure javascript and the other a jQuery plugin version (just for convenience).

Libraries

Pure Javascript library usage

<script type="text/javascript" src="https://github.com/sdecima/javascript-detect-element-resize/raw/master/detect-element-resize.js"></script>
<script type="text/javascript">
  var resizeElement = document.getElementById('resizeElement'),
      resizeCallback = function() {
          /* do something */
      };
  addResizeListener(resizeElement, resizeCallback);
  removeResizeListener(resizeElement, resizeCallback);
</script>

jQuery plugin library usage

<script type="text/javascript" src="https://github.com/sdecima/javascript-detect-element-resize/raw/master/jquery.js"></script>
<script type="text/javascript" src="https://github.com/sdecima/javascript-detect-element-resize/raw/master/jquery.resize.js"></script>
<script type="text/javascript">
  var myFunc = function() {
    /* do something */
  };

  $('#resizeElement').resize(myFunc);
  $('#resizeElement').removeResize(myFunc);
</script>

Compatibility

Works great on:

Known Issues:

Doesn't work on:

Please let me know if you test these libraries on any other browser, of if you run into issues with any of the above browsers.

TODO

Release Notes

v0.5.3

v0.5.2

v0.5.1

v0.5

v0.4.1

v0.4

v0.3

v0.2

v0.1

References

Similar libraries (but they use timers)

jQuery-mutate

jQuery-resize-plugin

Don't get me wrong, these are great libraries and work as advertised, it's just that they are not easy on browser resources.

External links

Back Alley Coder: Cross-Browser, Event-based, Element Resize Detection
Back Alley Coder: Overflow and Underflow Events