I want to make an alert when a div's innerText changes:
myDiv.addEventListener("change", function() {
if (myDiv.innerText != "some text")
alert('innerText has changed.');
},false);
Does not work.
I want to make an alert when a div's innerText changes:
myDiv.addEventListener("change", function() {
if (myDiv.innerText != "some text")
alert('innerText has changed.');
},false);
Does not work.
myDiv.addEventListener("DOMCharacterDataModified", function (event) { // ... add your code he }, false);
use DOMCharacterDataModified to detect innerText change event
MutationObserver
–
Lenten Posted on behalf of the OP.
I found a solution:
// THIRD FUNCTION (changes the text)
var i = 0;
function thirdFUN(){
i++;
var popo = document.getElementById('myDiv');
popo.innerText = i;
}
setInterval(thirdFUN, 500);
//---------------------------------------------------------------
// JQUERY
/*var popo = $('#myDiv');
$('#myDiv').bind("DOMSubtreeModified",function(){
if (popo.html() == "10")
console.log('changed');
});
*/
//---------------------------------------------------------------
// PURE JS
window.onload = function(){
var popo = document.querySelector('#myDiv');
var observer = new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
console.log(mutation.type); // <- It always detects changes
if (popo.innerHTML == "10"){
alert('hello');
}
});
});
var config = {characterData: true, subtree: true};
observer.observe(popo, config);
//observer.disconnect();
}
This is also a JS Fiddle.
The change
event isn't specified to fire at any point the text changes. It fires only when the textarea loses focus (the user clicks away or tabs away). So your event will only fire when this happens.
Aside from continually checking the value of the textarea with an interval, there is no elegant way to do this (to my knowledge).
Note in this fiddle that the change
event only fires after the textarea has lost focus.
See this answer for more info...
Can't comment on the top answer since not enough reputation, but according to MDN, Mutation Events (so including DOMCharacterDataModified) were deprecated and shouldn't be used anymore. Luckily, you can get the same thing with Mutation Observers now.
try
document.addEventListener("change", function()
......
© 2022 - 2024 — McMap. All rights reserved.
div
, is it a content editable, or just a regulardiv
? – Stampede