Chris Calo
Chris Calo

Reputation: 7828

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:

Upvotes: 11

Views: 8349

Answers (3)

mamacdon
mamacdon

Reputation: 3179

New browsers now have ResizeObserver, which fires when the dimensions of an element's content box or border box are changed.

const observer = new ResizeObserver(entries => {
  const entry = entries[0];
  console.log('contentRect', entry.contentRect);
  // do other work here…
});

observer.observe(element);

Upvotes: 7

Chris Calo
Chris Calo

Reputation: 7828

From a similar question How to know when an DOM element moves or is resized, there is a jQuery plugin from Ben Alman that does just this. This plugin uses the same polling approach outlined in Diodeus's answer.

Example from the plugin page:

// Well, try this on for size!
$("#unicorns").resize(function(e){
  // do something when #unicorns element resizes
});

Upvotes: 2

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114347

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)
     } 

}

Upvotes: 8

Related Questions