Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect DIV's dimension changed?

I've the following sample html, there is a DIV which has 100% width. It contains some elements. While performing windows re-sizing, the inner elements may be re-positioned, and the dimension of the div may change. I'm asking if it is possible to hook the div's dimension change event? and How to do that? I currently bind the callback function to the jQuery resize event on the target DIV, however, no console log is outputted, see below:

Before Resizeenter image description here

<html> <head>     <script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>     <script type="text/javascript" language="javascript">             $('#test_div').bind('resize', function(){                 console.log('resized');             });     </script> </head> <body>     <div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">         <input type="button" value="button 1" />         <input type="button" value="button 2" />         <input type="button" value="button 3" />     </div> </body> </html> 
like image 282
William X Avatar asked Jun 27 '11 12:06

William X


People also ask

How to detect div dimension change?

The observe() method of this object is used on the element that is to be tracked. This will check for any changes and execute the callback function when any dimension change is detected.

How do you find the width of an element?

To find the width and height of an element, width() and height() methods are used. The width() method is used to check the width of an element. It does not check the padding, border and margin of the element.


1 Answers

A new standard for this is the Resize Observer api, available in Chrome 64.

function outputsize() {  width.value = textbox.offsetWidth  height.value = textbox.offsetHeight } outputsize()  new ResizeObserver(outputsize).observe(textbox)
Width: <output id="width">0</output><br> Height: <output id="height">0</output><br> <textarea id="textbox">Resize me</textarea><br>

Resize Observer

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API

Spec: https://wicg.github.io/ResizeObserver

Current Support: http://caniuse.com/#feat=resizeobserver

Polyfills: https://github.com/pelotoncycle/resize-observer https://github.com/que-etc/resize-observer-polyfill https://github.com/juggle/resize-observer

like image 177
Daniel Herr Avatar answered Oct 13 '22 00:10

Daniel Herr