Philipp Philipp - 1 month ago 4x
jQuery Question

jQuery Call a function when content of a div changes

I have a span:

<span class="basket_amount">65.70</span>

This span is updated via an external script.
If the amount changes I want to trigger a javascript function.

$('.basket_amount').on('change', function() {

Currently it does not work. But why?

Thanks a lot!


If possible I would try to call the wished function from the other script. But if you really want to listen for changes on the element you can make use of DOMSubtreeModified. If you change the content via jQuery though it will call your function twice! Therefore use vanilla JavaScript for changing the content.

function versandkosten() {
    console.log('called versandkosten');
  var $basketAmount = $('.basket_amount');
  $basketAmount.bind("DOMSubtreeModified", versandkosten);

  // test changing the content of the element via JavaScript
  $basketAmount[0].innerHTML = 77;

  // changing it via jQuery would call it twice!
  // $basketAmount.html(77);