Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to animate numbers using Jquery

I am trying to animate a say $233 to $250 or decreasing from 250 to 233 ,i dont want to replace 233 by 250 instead i want a counter kind of effect and at the time of scrolling numbers zoom effect is also required. i am new to Jquery any help would be highly appreciated.

like image 905
dpsdce Avatar asked Mar 23 '11 20:03

dpsdce


2 Answers

HTML

<button id="start">Start</button>
<button id="reset">Reset</button>
<input id="counter" value="233"/>

JavaScript

$(function ()
{
    var $start = $('#start'),
        start = $start.get(0),
        $reset = $('#reset'),
        reset = $reset.get(0),
        $counter = $('#counter'),
        startVal = $counter.text(),
        currentVal = startVal,
        endVal = 250,
        prefix = '$',
        fontSize = $counter.css('font-size');

    $start.click(function ()
    {
        this.disabled = true;
        var i = setInterval(function ()
        {
            if (currentVal === endVal)
            {
                clearInterval(i);
                reset.disabled = false;
                $counter.animate({fontSize: fontSize});
            }
            else
            {
                currentVal++;
                $counter.text(prefix+currentVal).animate({fontSize: '+=1'}, 100);
            }
        }, 100);
    });

    $reset.click(function ()
    {
        $counter.text(prefix + startVal);
        this.disabled = true;
        start.disabled = false;
    }).click();
});

Demo →

like image 51
Matt Ball Avatar answered Oct 31 '22 22:10

Matt Ball


Googled this snippet and it looks pretty awesome and compact:

// Animate the element's value from 0% to 110%:
jQuery({someValue: 0}).animate({someValue: 110}, {
    duration: 1000,
    easing:'swing', // can be anything
    step: function() { // called on every step
        // Update the element's text with rounded-up value:
        $('#el').text(Math.ceil(this.someValue) + "%");
    }
});

Fiddle

like image 27
The Whiz of Oz Avatar answered Oct 31 '22 22:10

The Whiz of Oz