I would like to fire a function every time a div has a change in height. How can I do this?
-
1Here is a good example for your question : [http://stackoverflow.com/questions/9628450/jquery-how-to-determine-if-a-div-changes-its-height-or-any-css-attribute][1] [1]: http://stackoverflow.com/questions/9628450/jquery-how-to-determine-if-a-div-changes-its-height-or-any-css-attribute – Halil Bilgin Feb 09 '14 at 22:37
3 Answers
A good way is to use DOM mutations to verify every change in a specific part of the markup.
For example, you can use the jQuery mutate official plugin to detect if the height of something changed and launch a callback.
You can try this:
$('div.monitor').mutate('height',function (element,info){
console.log('a div with has changed it\'s height, the function below should do something about this...');
$(this).css('background','red');
});
$(document).ready(function(){
var divHeight = $("#share-something-textarea").css("height");
setInterval(function(){
if(divHeight !== $("#share-something-textarea").css("height")){
//something here
}
},200);
});
I think you can set a setInterval that verify every x ms the div height.
There are multiple ways to achieve this, anyway I think this solution is by far the best. There is a Jquery library called Jquery Mutate that was created right for things like these.
(Current Supported events: width, height, top, right, left, bottom, hide, show, scrollHeight, scrollWidth, scrollTop, scrollLeft).
If you would like to fire a function every time a div has a change in height, you can do something like this:
First import the library:
<script src="http://www.google.com/jsapi"></script>
<script> google.load("jquery",'1.7'); google.load("jqueryui", "1"); </script>
<script src="mutate.events.js"></script>
<script src="mutate.min.js"></script>
Then you can use this code:
$('#div').mutate('height',function (element,info){
console.log('a div changed it\'s height, the function below should do something about this...');
$(this).css('background','red'); <-- example of action triggered after the event height changed
});
Here you find the official website of Jquery Mutate: http://www.jqui.net/jquery-projects/jquery-mutate-official/
And a demo that shows how flexible it is: http://www.jqui.net/demo/mutate/

- 2,074
- 2
- 24
- 38