views:

8520

answers:

4

I've got a div that contains some content that's being added and removed dynamically, so its height is changing often. I also have a div that is absolutely positioned directly underneath with javascript, so unless I can detect when the height of the div changes, I can't reposition the div below it.

So, how can I detect when the height of that div changes? I assume there's some jQuery event I need to use, but I'm not sure which one to hook into.

Thanks.

+5  A: 

Haven't tested this but I think this will work:

$("#myDiv").bind("resize", function(){ 
                                       alert( $("#myDiv").height() ); 
                                     } 
                );

However, if you are changing the content of your DIV (#myDiv in the above example) dynamically, then I think it would be better to just modify that code to recalculate the height of the DIV ($("#myDiv").height()) after it changes the content of the DIV and then reposition the underlying DIV and not bother setting an event handler.

Bill
Doh, repositioning the div whenever I make changes to the content makes a lot sense. Thanks!
Bob Somers
bind('resize') only works on the window
DEfusion
+1  A: 

You can use the DOMSubtreeModified event

$(something).bind('DOMSubtreeModified' ...

But this will fire even if the dimensions don't change, and reassigning the position whenever it fires can take a performance hit. In my experience using this method, checking whether the dimensions have changed is less expensive and so you might consider combining the two.

Or if you are directly altering the div (rather than the div being altered by user input in unpredictable ways, like if it is contentEditable), you can simply fire a custom event whenever you do so.

Downside: IE and Opera don't implement this event.

eyelidlessness
DEfusion
True. Note added.
eyelidlessness
+3  A: 

Just a note for people that might actually want to use the resize function.

I was trying to detect resize on a div as well but apparently the resize binding is only for windows and frames: http://stackoverflow.com/questions/229010/jquery-resize-not-working-at-firefox-chrome-and-safari

828
A: 

There is a very good plugin to do this http://benalman.com/projects/jquery-resize-plugin/

p.s. yep, this thread is very old.

JLarky