1

Possible Duplicate:
Detecting when a div’s height changes using jQuery

I wonder if there's any function available to track changes to an element? I want to track height of an element and if reaches max-height, then addClass something.

By track i mean continuously, otherwise I'd just write an if statement.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • What is causing the height to change? Is this a general question or are you trying to accomplish something specific? – Wesley Murch Jan 16 '13 at 18:14
  • http://stackoverflow.com/questions/172821/detecting-when-a-divs-height-changes-using-jquery – lc. Jan 16 '13 at 18:14

2 Answers2

2

If you control the way the changes to the element are going to happen (For example, because you provided an interface for making those changes), you should implement your own callbacks system, or just run a function whenever a change happens.

If you do not control them, you must monitor the element periodically and check for changes, either with setInterval or recursive calls to setTimeout. Remember to clear the interval/break the timeout loop when you no longer need to monitor for changes, or if the element becomes unavailable. If you don't, any objects being referenced from within your callback will not be garbage-collected.

1

Use a setInterval, like this:

var maxHeight = 0;
setInterval(function() {
    if($("#myelement").height() >= maxHeight) {
        // do stuff when div is too tall
    }
}, 50);
Elliot Bonneville
  • 51,872
  • 23
  • 96
  • 123