Onresize for div elements?
Visual Studio highlighted my onresize
attribute of my div
tag, and says that it isn't a valid attribute for HTML5. Is this true? What should I use instead? It seems kind of silly that this would be the case.
Solution 1:
Microsoft's Internet Explorer supports onresize
on all HTML elements.
In all other Browsers the onresize
is only available at the window
object.
https://developer.mozilla.org/en-US/docs/Web/API/Window.onresize
If you wanna have onresize at a div
in all browsers check this:
http://marcj.github.io/css-element-queries/
This library has a class ResizeSensor
which can be used for resize
detection.
Solution 2:
Only Window.onResize
exists in the specification. Please remember that every IFrame
element creates new Window
object which supports onResize
. Therefore IMO the most reliable method to detect changes to the element's size is to append hidden iframes to the element.
If you are interested in a neat and portable solution, please check this plugin. It takes 1 line of code to listen the event of changing width or height of your div.
<!-- (1) include plugin script in a page -->
<script src="/src/jquery-element-onresize.js"></script>
// (2) use the detectResizing plugin to monitor changes to the element's size:
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });
// (3) write a function to react on changes:
function monitoredElement_onResize() {
// logic here...
}