9

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.

$(document).ready(function(){
    $('.basket_amount').on('change', function() {
        versandkosten();
    });  
});

Currently it does not work. But why?

Thanks a lot!

Philipp
  • 93
  • 1
  • 1
  • 3
  • Possible duplicate of [Jquery Event : Detect changes to the html/text of a div](http://stackoverflow.com/questions/15657686/jquery-event-detect-changes-to-the-html-text-of-a-div) – Mohammad Sep 10 '16 at 09:36

3 Answers3

8

The accepted answer uses the DOMSubtreeModified event, which is now deprecated.

Here is an updated answer using its replacement, the MutationObserver object.

$(document).ready(function(){
var observer = new MutationObserver(function(e) {versandkosten();});
observer.observe($('.basket_amount')[0], {characterData: true, childList: true});
});

Fiddle sample https://jsfiddle.net/9our3m8a/257/

See also https://javascript.info/mutation-observer

Cheekysoft
  • 35,194
  • 20
  • 73
  • 86
Julius
  • 387
  • 6
  • 15
6

Meanwhile deprecated! While this should still work, be aware that DOMSubtreeModified has been deprecated see also Mozilla Doc. Thx to @LuisEduardox for pointing this out.

The original post: 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');
}
$(document).ready(function(){
  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);
});

Fiddle: https://jsfiddle.net/9our3m8a/

Michael Troger
  • 3,336
  • 2
  • 25
  • 41
4

Try this one

 $('.basket_amount').bind("DOMSubtreeModified",function(){
      versandkosten();
    });
Nasir
  • 421
  • 7
  • 21