hey would there be anyway to connect an MutationObserver and then disconnect it with the same button i know how to disconnect and connect it but i would only like to do it with one button how can i do this? sorry my bad english
var target = document.getElementsByClassName('message')[0]; var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { console.info("EVENT TRIGGERT "); }); }); var config = { attributes: true, childList: true, characterData: true }; function dis() { observer.disconnect(); } function obs() { observer.observe(target, config); } // simulate change refreshIntervalId = setInterval(function() { document.getElementsByClassName('message')[0].innerHTML = Math.random().toString(36).substring(2, 15); }, 1000); //
<button onclick="obs();">observe</button> <button onclick="dis();">disconnect</button> <div class="message"></div>
Keep track of you observer state in another variable (eg isObserving
). Set this variable to true
in your obs()
function, set it to false
in dis()
and call a toggleObs()
with your button.
function toggleObs() {
if(isObserving) {
dis();
} else {
obs();
}
}
there is no property on observable which will tell you if you observing or not. For that reason you need to keep track by your self. See example https://stackblitz.com/edit/js-dw5jmr
let isObserving = false;
window.toggleObserve = function() {
isObserving = !isObserving;
isObserving ? window.obs() : window.dis();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.