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 MutationObservers if supported by the browser, and overflow and underflow events if not. It also uses the 'onresize' event on IE10 and below.
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:
- only available as jQuery libraries (so no standalone Javascript)
- 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 to do event-based element resize detection; and it works great without consuming resources at all (just like any other browser originated event).
On the other hand, most new browsers implement WC3 DOM4 MutationObservers, which allows to observe property changes and hence indirectly watch for resize changes.
The libraries on this repository are just a concrete implementation of a mixture of the above technologies/techniques.
<script type="text/javascript" src="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><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.resize.js"></script>
<script type="text/javascript">
var myFunc = function() {
/* do something */
};
$('#resizeElement').resize(myFunc);
$('#resizeElement').removeResize(myFunc);
</script>Works great on:
- Chrome
- Firefox
- IE 10 and below (tested on 10, 9, 8 and 7)
Works but limited:
- IE 11: due to lack of onresize/overflow events, it only detects changes through a MutationObserver;
i.e. only javascript generated resize changes and not CSS pseudo classes e.g. :hover, CSS animations, etc.
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.
- Create minified version of the libraries.
- Add support for standard jQuery bind method on 'resize' event.
- Adds better cross-browser support, it now uses MutationObservers only on IE11.
- Adds support for MutationObservers.
- Adds support for IE 11.
- Wrapped the pure javascript version of the library (to hide non-public methods).
- Adds support for IE 8 and below.
- Implementation based on the works of Back Alley Coder
- Adds jQuery plugin version
Don't get me wrong, these are great libraries and work as advertised, it's just that they are not easy on browser resources.
Back Alley Coder: Cross-Browser, Event-based, Element Resize Detection
Back Alley Coder: Overflow and Underflow Events