Search code examples
javascriptjquerywordpressmutation-observers

Replace dot with comma of text which is not in DOM while loading


I'm using a WordPress Theme and need to modify the output of a counter animation. While the page is loading, there is an empty span like this:

<span class="counter"></span>

After the animation is finished, the span looks like this:

<span class="counter">30.5</span>

Since it is a german website the output needs to be with a comma instead of a dot, so it should look like this: 30,5
How can I achieve this?

Reading similar posts it looks like I need a WebKitMutationObserver (?) but I have no experience using it. Thanks for any help!


Solution

  • const elCounter = $('#counter');
    
    $('button').on('click', () => {
      $({progress: 0}).animate(
        {progress: 1000}, {
        duration: 30000,
        step: val =>  {
          elCounter.text((val / 10).toFixed(2));
        }}
      )
    });
    
    new MutationObserver(() => {
      const replacement = elCounter.text().replace('.', ',');
      
      if(elCounter.text() !== replacement){
        elCounter.text(replacement);
      }
    })
    .observe(elCounter[0], { childList: true });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="counter">0</div>
    <button>Go progress</button>