2

I am stuck. I am trying to get jquery to on load of the page generate an animation using numbers. So that the number 5 would be switching between 0 - 9 until the allotted time was up or if I have 50 the 5 would be going through 0 - 9 and the 0 would also being going through 0 - 9.

Thank you all for your answers and suggestions.

2
  • 3
    Please post what you've tried yourself, and where you got stuck. Have you tried anything at all? Commented Dec 2, 2011 at 23:26
  • The part I am stuck at is the animation itself. I was not sure how to start the animation. Commented Dec 3, 2011 at 0:27

4 Answers 4

13

I was bored. Here:

(function($){
    $.fn.extend({
        numAnim: function(options) {
            if ( ! this.length)
                return false;

            this.defaults = {
                endAt: 2560,
                numClass: 'autogen-num',
                duration: 5,   // seconds
                interval: 90  // ms
            };
            var settings = $.extend({}, this.defaults, options);

            var $num = $('<span/>', {
                'class': settings.numClass 
            });

            return this.each(function() {
                var $this = $(this);

                // Wrap each number in a tag.
                var frag = document.createDocumentFragment(),
                    numLen = settings.endAt.toString().length;
                for (x = 0; x < numLen; x++) {
                    var rand_num = Math.floor( Math.random() * 10 );
                    frag.appendChild( $num.clone().text(rand_num)[0] )
                }
                $this.empty().append(frag);

                var get_next_num = function(num) {
                    ++num;
                    if (num > 9) return 0;
                    return num;
                };

                // Iterate each number.
                $this.find('.' + settings.numClass).each(function() {
                    var $num = $(this),
                        num = parseInt( $num.text() );

                    var interval = setInterval( function() {
                        num = get_next_num(num);
                        $num.text(num);
                    }, settings.interval);

                    setTimeout( function() {
                        clearInterval(interval);
                    }, settings.duration * 1000 - settings.interval);
                });

                setTimeout( function() {
                    $this.text( settings.endAt.toString() );
                }, settings.duration * 1000);
            });
        }
    });
})(jQuery);

Test HTML:

<span id="number"></span>

Usage:

$("#number").numAnim({
    endAt: 97855,
    duration: 3
});
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but is there a way to make it so the number it ends up being is set? I want it to do the animation an then come to the same number every time.
Awesome, Question: why do you make defaults and then add the usage part? Also on your example I tried to add another one but it would on display it once is there way to display two numbers doing this?
Usage is to show you how to override the defaults when you call the plugin. The reason more than one doesn't work, and I'm guessing at your code here, is because you simply duplicated the span tag and left the ID the same. Change id= to class= and update the jQuery selector to .number.
But wouldn't you want that in the function itself? No I am an even bigger idiot then that called the wrong div lol
What I've given you is a jQuery plugin. Most plugins revolve around being able to accept parameters so you never have to touch the plugin source code when you want to change something. In other words, store my answer's first block of JavaScript in jquery.numanim.js, include it in your page, and have your page use my answer's second block of js.
2

Here's a simple solution, commented and light on the jQuery.

Basically, you can use setInterval to run some function every X milliseconds. When the duration is expired, or you have your desired value, you can clearInterval which stops the cycle completely.

Working example: http://jsfiddle.net/ZDsMa/1

var output, started, duration, desired;

// Constants
duration = 5000;
desired = '50';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        clearInterval(animationTimer);
    } else {
        // Generate a random string to use for the next animation step
        output.text(
            ''+
            Math.floor(Math.random() * 10)+
            Math.floor(Math.random() * 10)
        );
    }
}, 100);

Comments

2

here it is random number changer with jquery using animate effect. http://jsfiddle.net/ZDsMa/94/

var output, started, duration, desired;

// Constants
duration = 5000;
desired = '50';

// Initial setup
output = $('#output');
started = new Date().getTime();

// Animate!
animationTimer = setInterval(function() {
    // If the value is what we want, stop animating
    // or if the duration has been exceeded, stop animating
    if (output.text().trim() === desired || new Date().getTime() - started > duration) {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );

    } else {
        console.log('animating');
        // Generate a random string to use for the next animation step
        output.text('' + Math.floor(Math.random() * 990)

        );
    }
}, 1000);

you can change the values in it

1 Comment

This doesn't work as the user asked, in fact it doesn't work properly at all! I just tested it and it didn't stop on the desired number and you are not clearing the interval - so the loop continues each second, forever more, even though the 'animation' has stopped. I'm shocked you have been upvoted for this, especially as you posted it a year after Alex Wayne's answer, which is almost identical, but most importantly, a year after an answer was accepted! If you insist on posting duplicate answers on closed questions, make sure they work first buddy.
0

If you want a way to randomise a number in jquery try

Math.floor(Math.random()*100)

Math.random() creates a number between 0.0 and 1.0

5 Comments

I think he wants help with the effects, not the generation of the random number...
That is NOT jQuery. That is JavaScript.
@SeanHJenkins jQuery is a library written in JavaScript. Your code snippet does not do anything "in jQuery" as you claim. It illustrates Math.random() a function provided by the standard JavaScript runtime. And the distinction is important, especially for beginners because they treat jQuery as it's own language and never learn good JavaScript. And that is a tragedy; a tragedy I want to avoid here. Write JS. Use jQuery!
Why so padantic Squeegy? I know JQuery is a library.
Because it's confusing for newcomers. People that learn jQuery without learning javascript (or even realize they are using it) usually write horrible code because they don't ever understand how javascript works. You'd be very surprised how often these things are confused. It's like writing a RubyOnRails app without ever learning ruby. See Rebecca Murphy's slide on the jQuery divide: slideshare.net/rmurphey/the-jquery-divide-5287573 jQuery is a tool for javascript developers, and making that difference known helps everyone trying to learn this stuff.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.