Muhammed Muneer
Muhammed Muneer

Reputation: 123

Can i add a comma (,) dynamically to a CSS pseudo element which its value is coming from CSS variable

I want to insert the commas appropriately between the numbers. eg: 6,350

is there any way I can achieve this in the following scenario

setTimeout(function () {
  $('.number-counter').each(function () {
    $(this).addClass('inView');
  });
}, 500);
@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number-counter {
  transition: --num 3s;
  counter-set: num var(--num);
  font: 800 40px system-ui;
}
.number-counter::after {
  content: counter(num);
}
.number-counter.inView {
  --num: var(--count);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="number-counter" style="--count: 6350;"></div>

Upvotes: 2

Views: 629

Answers (1)

Kosha Sanghvi
Kosha Sanghvi

Reputation: 144

I have tried to add this code in CSS but there is no way to count the digits in CSS so I have added the comma(,) using jQuery. I hope this will help you. It will add the comma after 3 digit.

setTimeout(function () {
  jQuery('.number-counter').each(function () {
    jQuery(this).addClass('inView');
    var $this = jQuery(this);
     countTo = $this.attr('data-count');
  jQuery({ countNum: $this.text()}).animate({countNum: countTo},
    {     
      easing: 'linear',
      step: function() {
              $this.text(commaSeparateNumber(Math.ceil(this.countNum)));
  },
  complete: function() {
    $this.text(commaSeparateNumber(Math.ceil(this.countNum)));
      }
    });
  });
}, 500);
function commaSeparateNumber(val) {
  while (/(\d+)(\d{3})/.test(val.toString())) {
    val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
  }
  return val;
}
@property --num {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

.number-counter {
  transition: --num 3s;
  counter-set: num var(--num);
  font: 800 40px system-ui;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="number-counter" style="--count: 6350;" data-count="6350"></div>

Upvotes: 1

Related Questions