Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery resize listener on a div

This is the situation, I have 2 div's next to each other. One div is very dynamic in height, which basically means it can grow and shrink to accommodate for it's content. For example, this div has content that can be folded open or close, or containers that can expand to fit ajax loaded content.

Now, next to this div is another one that neatly follows the height of the first one through css. Works great. But here is the question: I would like to change the content of this second div depending on its height.

In other words, div 1 changes in size, div 2 follows through css and I now need to trigger an ajax call to re-fill div 2 with new content, befitting it's new size.

Has anybody an idea how I can do this with jquery? If possible, without the use of timeouts?

Cheers.

like image 461
Peter Avatar asked Nov 08 '11 16:11

Peter


People also ask

How to resize in jQuery?

The resize() method is an inbuilt method in jQuery which is used when the browser window changes its size. The resize() method triggers the resize event or attaches a function to run when a resize event occurs. jQuery has a built-in method for window resize events. This syntax is used for cross-browser resize events.

How does jQuery determine Div resize?

The values of the dimensions are compared with the values of the older iteration to check if there is any difference. The height and width of the element to be tracked is found out using the height() and width() method in jQuery.

How does Div know resize?

In the mean time, you can use function like the following. Since, the majority of element size changes will come from the window resizing or from changing something in the DOM. You can listen to window resizing with the window's resize event and you can listen to DOM changes using MutationObserver .


2 Answers

As the thread poelinca provided suggests, there are some nice plugins available for this functionality.

If you don't like the plugin idea, another simple solution would be to simply trigger a "resize" event on the div whenever the content is modified. Then you could monitor it with resize() as expected, utilizing an elegant observer pattern.

function appendContent($div, content) {
   $div.append(content).trigger($.Event('resize'));
}

$div.bind('resize', function(e) {
   // all your magic resize mojo goes here
});
like image 184
Kato Avatar answered Oct 30 '22 23:10

Kato


https://github.com/sdecima/javascript-detect-element-resize

Works like a charm!

I´ve tested attrchange but this was not working, lost 2hours of work :(

like image 21
Jaroslav Štreit Avatar answered Oct 30 '22 23:10

Jaroslav Štreit