Reputation: 7365
Let's say I have the following HTML:
<div id='content'></div>
I'd like to be alerted when height mutations occur on this element. I was hoping the MutationObserver class would help in this, but here is my problem with it:
document.querySelector('#content').style.height = '100px'
It triggers my callback like expected, however normal user interactions won't trigger this, e.g., http://jsfiddle.net/wq4q9/2/
My question is, what is the best modern approach for checking if an element's height has changed?
No jQuery please.
Upvotes: 5
Views: 1828
Reputation: 75307
You'll probably have to go along with T.J. Crowders recommendation to poll, however your code example isn't working for other reasons (it seems):
The documentation* for childList
says that it is used to monitor additions and removals of the target node's child elements.
* This is the first and only time I'll reference MSDN as opposed to MDN, because the MDN documentation for this is crap.
The record you should be observing is subtree:
Set to true to also monitor changes to all the target node's descendants
If you do that, then the code works in Firefox.
var target = document.querySelector('#content');
var observer = new MutationObserver(function(mutations) {
console.log(mutations);
});
var config = { attributes: true, childList: true, subtree: true, characterData: true };
observer.observe(target, config);
document.querySelector('button').addEventListener('click',function(){
target.style.height = '200px';
});
However, it still doesn't work in Chrome; likely because of the Chrome bug reported in this question.
Upvotes: 1
Reputation: 1074148
I don't think there's anything you can do other than poll. (Another way your observer wouldn't be triggered would be if you changed a CSS rule that applied to the element, changed its parent's size and its size was dependent on that, added a new style sheet that affected it...)
Upvotes: 1