1

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!

lefty
  • 33
  • 4
  • So you can not change the code that puts the text in there? Is there no event for the code that updates it? – epascarello May 17 '23 at 19:16
  • Unfortunately not really. The client is using a theme with prebuilt widgets like the counter animation. If i modfify the JS files directly, the changes will disappear if the theme gets an update. Hard to explain. :/ – lefty May 17 '23 at 20:09
  • https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom – epascarello May 17 '23 at 20:11

2 Answers2

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>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17
0

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>
Sai Manoj
  • 3,809
  • 1
  • 14
  • 35
  • Thanks, but I can not modify the inside of the span (it is empty while the page is loading, the value is stored somewhere else). That's why the mutation-observer is needed and the solution from @silent-mantra is working. – lefty May 18 '23 at 07:38