How to detect resize of any element in HTML5

Yes there is not simple solution, that's not good.

I've found something very useful for this.: cross browser event based element resize

It's tricky, appending some needed html to the element that have to be listened and detects scrolling event.

Some html example from that page:

<div class="resize-triggers">
    <div class="expand-trigger"><div></div></div>
    <div class="contract-trigger"></div>
</div>

Also Some JS:

var myElement = document.getElementById('my_element'),
    myResizeFn = function(){
        /* do something on resize */
    };
addResizeListener(myElement, myResizeFn);
removeResizeListener(myElement, myResizeFn);

But it works for elements those are able to have children, not for self-closing tags.

You can see the demo http://jsfiddle.net/3QcnQ/67/


As of July 2020, ResizeObserver is still un-official in W3C nor WhatWG but it is already supported by all major browsers since support Safari 13.1 since 2020-Mar-24.


FYI, there's a spec for a new ResizeObserver API. Chrome seems to be the only browser that has implemented it as of Aug 2018 (see caniuse.com), but there's at least one polyfill you can use now (which uses MutationObserver).


Well, there is a easy library for that. Although there's nothing official how to listen on dimension changes of all types of elements and only window supports it at the moment we have luckily a polifill for that that works very accurate and supports all browsers even inclusive IE6+.

https://github.com/marcj/css-element-queries

You can find there a class ResizeSensor. To setup a listener on a element you can just do:

new ResizeSensor($('.myelements'), function() {
    console.log('changed');
});