Is there any way to watch, if the content within a div changes?
Let's say I have:
<div id="hello"><p>Some content here</p></div>
Which at some point 5 seconds later changes to:
<div id="hello"><ul><li>This is totally different!</li></ul></div>
How can I be notified of this via a callback or something else? I can in most cases get the javascript that's doing the inserting, to tell me. But I wanted to know if it was possible.
Maybe, it's reasonable to monitor the source of events that amend the contents of your layer(s)? Say, a user has clicked anywhere (read, "did a click") after what the contents may had changed. So if you check the .html() after a click rather than using a loop - it might save some system resources.
Who/what will change this? If it's some JS you control, use that to also trigger your callback. Obviously a user cannot change this.
If you want to watch a
<input>
element etc, use the 'change' event. jQuery version here: http://api.jquery.com/change/Here's a code sample that calls a simple alert when the given value changes:
The jQuery .change() method works only for form fields.
I wrote a little jQuery plugin for you:
Be aware that this watches changes in the contents of the element (html) only, not the attributes.
There are some events called
DOMNodeInserted
,DOMNodeRemoved
andDOMSubtreeModified
. Which check is there any elements are added or removed or any inner Html changed inside a div. for this you need ansetInterval()
function.The above functions will checks the Div for any content change, for every second
There is no native jQuery/DOM event that will fire when HTML/DOM content changes.
You could (if you are feeling particularly wasteful) do something like this:
Just remember, calling
.html()
every 100ms is probably not the best idea for your sites performance.jsFiddle mockup