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.
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.
- 1 Are you looking to do this yourself or do you have a library available to you? If you have jQuery, might want to check out the jQuery watch plugin – LoveAndCoding Commented Nov 13, 2012 at 15:09
- You could trigger a event when you change the content? – Allan Kimmer Jensen Commented Nov 13, 2012 at 15:11
- Thanks, Ktash and Allan. Care to post any examples? I'd prefer to accept an answer with working code. – Chris Calo Commented Nov 13, 2012 at 15:16
3 Answers
Reset to default 8There 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)
}
}
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);
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
});