MrDikke MrDikke - 1 year ago 69
Javascript Question

Creating a fancy calculation for price in Javascript?

I've got 2 prices:

Price1: $5000

Price2: $2000

What I want is JavaScript to calculate the total live on the page, so when the div loads, that it starts calculating.

But I don't just want to instantly see $7000 right there. I want it to 'animate' the result. So go from $0 to $1, $2, $3, $4, $5 ... $5000, $5001, $5002 ... $7000.

I also want the price that it's currently adding below the line that's adding to.



Currently adding: Price1

Is this possible? If so how?

Answer Source

jQuery lets you .animate()Docs any arbitrary value.
Access the current animated now value using the step method callback

var tot  = 0,
    $p1  = $("#p1"),
    $p2  = $("#p2"),
    $tot = $("#tot");

function animateTotal() {

  tot = parseFloat($p1.val()) + parseFloat($p2.val());

  $({ p: 0 }).animate({ p: tot }, {
    duration: 2000,
    easing: "swing",   // "swing" is default, you can try another easing like "linear"
    step: function (now) {
      $tot.val( now.toFixed(2) );


$p1.add($p2).on("input", animateTotal);
<script src=""></script>
$<input value="3000.50" id="p1" name="p1">PRICE1 +<br>
$<input value="4000" id="p2" name="p1">PRICE2 =<br>
$<input value="0" readonly id="tot" name="tot">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download