0

I have a working number counter section on a site I'm working on and I don't know much JS, I have some code that works but it breaks the front-end and stops the counter. I'm hoping someone can help me understand how to put the pieces I have together correctly.

I've tried both the functions separately and together, probably incorrectly. The second function which deals with the thousand comma works, however it kicks out the front end and the counting function.

I'm not sure what happened with the #shiva element, but I've replaced this overall with #counter as the function works across the board rather than one div element only. I've left both in just now in case theres another way.

HTML:

<div id="counter">
    <div class="row">
        <div class="col span-1-of-2">
            <div class="row">
                <div id="shiva"><span class="count">1688019</span></div>
                <h2>Text</h2>
            </div>

            <div class="row">
                <div id="shiva"><span class="count">82150</span></div>
                <h2>Text</h2>
            </div>
        </div>

        <div class="col span-1-of-2">
            <div class="row">
                <div id="shiva"><span class="count">10505</span></div>
                <h2>Text</h2>
            </div>

            <div class="row">
                <div id="shiva"><span class="count">168260</span></div>
                <h2>Text</h2>
            </div>

        </div>
    </div>
    </div>

Counter:

$('.count').each(function () {
    $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
    }, {
        duration: 2000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

Separator:

    function numberWithCommas(number) {
    var parts = number.toString().split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
}

$('#counter').each(function () {
    var num = $(this).text();
    var commaNum = numberWithCommas(num);
    $(this).text(commaNum);
});
Caitlin
  • 531
  • 5
  • 19

1 Answers1

2

Someone answered using a similar example to comma by thousands, you just had to adapt it for your situation. Read here How to print a number with commas as thousands separators in JavaScript

The counter you need to replace it after it animates,

 $('.count').each(function () {
        $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
        }, {
            duration: 2000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
                $(this).text(convert($(this).text()))
            }
        });
    });

Steps:

  • Loop through each .count element
  • Replace each .count number by our functions return result
  • Our function uses regexp to format the string, combining and joining
  • Set the value in .count to our new result

Example

  

 const convert = str => {
        // Find the number
        let regx = /(\d{1,3})(\d{3}(?:,|$))/;
        // Set a variable
        let currStr;
        // Start loop
        do {
            // Replace current string, split it
            currStr = (currStr || str.split(`.`)[0])
                .replace(regx, `$1,$2`)
        } while (currStr.match(regx)); // Loop

        // Return our result from function
        return (str.split(`.`)[1]) ?
            currStr.concat(`.`, str.split(`.`)[1]) :
            currStr;
    };


    function total() {
        let total = 0;
        $('.count').each(function() {
           let v = parseInt($(this).text());
           total = v + total
        })
        return total;
    }

    $('.count').each(function () {
        $(this).prop('Counter', 0).animate({
            Counter: $(this).text()
        }, {
            duration: 2000,
            easing: 'swing',
            step: function (now) {
                $(this).text(Math.ceil(now));
                $(this).text(convert($(this).text()))
            }
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">
    <div class="row">
        <div class="col span-1-of-2">
            <div class="row">
                <div id="shiva"><span class="count">1688019</span></div>
                <h2>Text</h2>
            </div>

            <div class="row">
                <div id="shiva"><span class="count">82150</span></div>
                <h2>Text</h2>
            </div>
        </div>

        <div class="col span-1-of-2">
            <div class="row">
                <div id="shiva"><span class="count">10505</span></div>
                <h2>Text</h2>
            </div>

            <div class="row">
                <div id="shiva"><span class="count">168260</span></div>
                <h2>Text</h2>
            </div>

        </div>
    </div>
</div>
ABC
  • 2,068
  • 1
  • 10
  • 21
  • This works well but the counting function does not work now. – Caitlin Mar 25 '19 at 16:39
  • @CaitlinMooney this isn't meant to be added to your code. This is to substitute your code. It is the complete script and HTML. You put the Javascript in the `` and the html in your body. – ABC Mar 25 '19 at 16:41
  • I see what you want, you wanted a counter too. – ABC Mar 25 '19 at 16:43
  • Yes this is what I did, now the counter does not count but is static. I previously had a counter which animates from 0 to given number. – Caitlin Mar 25 '19 at 16:43
  • @CaitlinMooney can you check now? – ABC Mar 25 '19 at 16:58
  • Works brilliant now, thanks for the help, I'll have a look over it and make some reference notes! – Caitlin Mar 25 '19 at 17:00
  • @CaitlinMooney I notice the animation works, and replaces the commas. But I noticed the total is not accurate, im fixing that. Just give me a bit. – ABC Mar 25 '19 at 17:03
  • Sorry i clocked off yesterday, Glad you got your solution, just thought i'd note that you can use `val.toLocaleString('en')` to add commas to your numbers (make sure val is a number and not a string by prepending `+` to `val` e.g `val = +val`) – Francis Leigh Mar 26 '19 at 10:57
  • 1
    its works with `3.3.1/jquery.min.js` but not with `jquery/jquery.min.js?ver=3.5.1` – MAZ Apr 01 '21 at 10:00
  • @MAZ Thanks for the notice, I advise OP to take note. – ABC Apr 02 '21 at 05:41