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.

Jacinto
  • 558
  • 2
  • 9
  • 24

4 Answers4

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
});
simshaun
  • 21,263
  • 1
  • 57
  • 73
  • 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. – Jacinto Dec 03 '11 at 00:25
  • 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? – Jacinto Dec 03 '11 at 01:05
  • 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`. – simshaun Dec 03 '11 at 01:10
  • But wouldn't you want that in the function itself? No I am an even bigger idiot then that called the wrong div lol – Jacinto Dec 03 '11 at 01:40
  • 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. – simshaun Dec 03 '11 at 01:43
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

  • 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. – TheCarver Nov 11 '14 at 23:11
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);
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
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

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
Sean H Jenkins
  • 1,770
  • 3
  • 21
  • 29
  • I think he wants help with the *effects*, not the generation of the random number... – David Thomas Dec 02 '11 at 23:53
  • 1
    That is *NOT jQuery*. That is *JavaScript*. – Alex Wayne Dec 03 '11 at 00:18
  • 1
    @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!** – Alex Wayne Dec 03 '11 at 01:17
  • Why so padantic Squeegy? I know JQuery is a library. – Sean H Jenkins Dec 03 '11 at 10:24
  • 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: http://www.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. – Alex Wayne Dec 04 '11 at 00:30