Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MutationObserver on span text change does not trigger

This is just a boiled down example not an actual thing.

Still MutationObserver isn't firing so my assumption on how it works is wrong.

JSFiddle

$(function() {
  var editButtonVisibility = function() {
    console.log('bam');
  }

  $('#RiskPostcodeSummary span').on("change", function() {
    console.log("pew pew");
  });

  var observer = new MutationObserver(function(e) {
    editButtonVisibility();
  });

  observer.observe($('#RiskPostcodeSummary span')[0], {
    characterData: true
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
  <span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />

Why isn't MutationObserver firing when I change text in <span>?

like image 805
Matas Vaitkevicius Avatar asked Nov 04 '15 11:11

Matas Vaitkevicius


1 Answers

Adding childList: true fixes the problem.

From https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver:

childList: Set to true if additions and removals of the target node's child elements (including text nodes) are to be observed.

In your example, you're changing the text node child of the span element.

console.log("-");
$(function() {
  var editButtonVisibility = function() {
    console.log('bam');
  }

  $('#RiskPostcodeSummary span').on("change", function() {
    console.log("pew pew");
  });

  var observer = new MutationObserver(function(e) {
    editButtonVisibility();
  });

  observer.observe($('#RiskPostcodeSummary span')[0], {
    characterData: true,
    childList: true
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="RiskPostcodeSummary">
  <span></span>
</div>
<input type="button" value="click" onClick="$('#RiskPostcodeSummary span').text('sdfsdf');" />
like image 155
Rick Hitchcock Avatar answered Nov 12 '22 08:11

Rick Hitchcock