skip to Main Content

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!

2

Answers


  1. 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>
    Login or Signup to reply.
  2. Using value.toLocaleString('en-de',{...}) will solve your purpose

    const counterElement = document.querySelector('.counter');
    const value = parseFloat(counterElement.textContent);
    const formattedValue = value.toLocaleString('en-de', {
      minimumFractionDigits: 1,
      maximumFractionDigits: 1
    });
    counterElement.textContent = formattedValue;
    <span class="counter">30.5</span>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search