Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen for layout changes on a specific HTML element?

What are some techniques for listening for layout changes in modern browsers? window.resize won't work because it only fires when the entire window is resized, not when content changes cause reflow.

Specifically, I'd like to know when:

  • An element's available width changes.
  • The total height consumed by the in-flow children of an element changes.
like image 910
Chris Calo Avatar asked Nov 13 '12 14:11

Chris Calo


People also ask

How can I tell if a div is resized?

The height and width of the element to be tracked is found out using the height() and width() method in jQuery.

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

There are no native events to hook into for this. You need to set a timer and poll this element's dimensions in your own code.

Here's the basic version. It polls every 100ms. I'm not sure how you want to check the children's height. This assumes they'll just make their wrapper taller.

var origHeight = 0;
var origWidth = 0;
var timer1;

function testSize() {
     var $target = $('#target')     
     if(origHeight==0) {
         origWidth = $target.outerWidth();
         origHeight = $target.outerHeight();

     }
     else {
         if(origWidth != $target.outerWidth() || origHeight = $target.outerHeight()) {
             alert("change");  
         }
         origWidth = $target.outerWidth();
         origHeight = $target.outerHeight();
         timer1= window.setTimeout(function(){ testSize() }),100)
     } 

}
like image 182
Diodeus - James MacFarlane Avatar answered Oct 28 '22 00:10

Diodeus - James MacFarlane