Reputation: 53
Is there a eventListener who is just checking the changes of an innerText?
Example:
12345
I just want to check if "12345" is changing to something else like "23415".
There is no "click" event that will comes up or anything else. I don't have the chance to go through the code where the updates from the span's are coming. So I really can just only grab the event from the changes in the span element but I don't have any clue how.
Sorry for my bad English and thanks!
Upvotes: 5
Views: 7725
Reputation: 569
Just in case anyone is looking for a way to do this for multiple nodes. fiddle Further reading
HTML
<span class="observable" contenteditable="true">13436</span>
<span class="observable" contenteditable="true">13235</span>
JS
var observables = document.querySelectorAll('.observable');
console.log(observables);
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
var config = {
characterData: true,
subtree: true
};
observables.forEach(function(node) {
observer.observe(node, config);
});
Upvotes: 2
Reputation: 360
The accepted answer might not work on all browsers if the text being updated via the innerHTML
property. In this case, Firefox (as of 28) treats this as a childList
event type, while Chrome (as of 33) treats this as a characterData
event type. My guess is Chrome checks if the child node being update is a text node.
Firefox will fire characterData
mutation events if the text is updated via user input (like via contenteditable
as in the example).
In conclusion, if you want to watch for Javascript updating the innerHTML
of an element, make sure to add childList:true
to your MutationObserverInit
object to be compatible with Firefox.
Upvotes: 0
Reputation: 5319
Check out the MutationObserver. Using it you can listen to changes of the observed element's characterData
. Example:
<span class="observable" contenteditable="true">12345</span>
var observables = document.querySelector('.observable');
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
var config = {characterData: true, subtree: true};
observer.observe(observables, config);
Note that subtree
has to be true
because the text actually is a child element of the observed element.
Upvotes: 6