I have this mutation observer function below. The issue is that if the condition is met for “false” that console.log will log many times in the browser. I think the best way to fix this is to add something in here that if the mutation is met don’t run function.
Does adding in mutationObserver.disconnect(); after the else if condition the best way to accomplish this?
JavaScript
x
25
25
1
window.addEventListener('DOMContentLoaded', (event) => {
2
3
// Listening to Class Changes //
4
var mutationObserver = new MutationObserver(function (mutations) {
5
mutations.forEach(function (mutation) {
6
var change = mutation.target.classList.contains('hidden-class');
7
if (change === true) {
8
return true;
9
}
10
else if (change === false) {
11
console.log('this mutation is visible');
12
}
13
});
14
})
15
mutationObserver.observe(document.getElementById('cart-wrapper'), {
16
attributes: true,
17
characterData: true,
18
childList: true,
19
subtree: true,
20
attributeOldValue: true,
21
characterDataOldValue: true
22
});
23
24
});
25
Advertisement
Answer
Use .some
instead, to iterate over the mutations and see if any of the targets’ classLists contain the class:
JavaScript
1
11
11
1
var mutationObserver = new MutationObserver(function (mutations) {
2
const somethingJustMutatedIsHidden = mutations.some(
3
mutation => mutation.target.classList.contains('hidden-class')
4
);
5
if (somethingJustMutatedIsHidden) {
6
// do something?
7
} else {
8
console.log('this mutation is visible');
9
}
10
})
11
Keep in mind that forEach
ignores its return value; the return true
you currently have doesn’t do anything.