Is it possible to simply add event listeners to certain elements to detect if their height or width have been modified? I’d like do this without using something intensive like:
$(window).resize(function() { ... });
Ideally, I’d like to bind to specific elements:
$("#primaryContent p").resize(function() { ... });
It seems like using a resize handler on the window is the only solution, but this feels like overkill. It also doesn’t account for situations where an element’s dimensions are modified programatically.
Here is a jQuery plugin with
watchandunwatchmethods that can watch particular properties of an element. It is invoked as a method of a jQuery object. It uses built-in functionality in browsers that return events when the DOM changes, and usessetTimeout()for browsers that do not support these events.The general syntax of the
watchfunction is below:propsis a comma-separated string of the properties you wish towatch (such as
"width,height").funcis a callback function, passed the parameterswatchData, index, wherewatchDatarefers to an object of the form{ id: itId, props: [], func: func, vals: [] }, andindexis the index of the changed property.thisrefers to the changed element.intervalis the interval, in milliseconds, forsetInterval()in browsers that do not support property watching in the DOM.idis an optional id that identifies this watcher, and is used to remove a particular watcher from a jQuery object.The general syntax of the
unwatchfunction is below:idis an optional id that identifies this watcher to be removed. Ifidis not specified, all watchers from the object will be removed.For those who are curious, the code of the plugin is reproduced below: