AdBlock Detected

We provide high-quality source code for free. Please consider disabling your AdBlocker to support our work.

Buy me a Coffee

Saved Tutorials

No saved posts yet.

Press Enter to see all results

jQuery dynamic number ticker

By pushpam abhishek
Listen to this article

jQuery dynamic number ticker

In this article A fascinating little script that helps you display a dynamic JSON feed of numbers that automatically updates on the page by animating up or down to the current number.

jQuery dynamic number ticker


The JS Code

There are three functions in total. The first one ‘format_number’ which works the same as number_format(); in PHP adding the decimal places. In the ‘magic_number’ function then takes the current number and the new number and animates between them.

you have the ‘update’ function which retrieves the new data set of numbers via a JSONP feed. At the bottom of the script, you are refreshing the data every 4 seconds. Oh and don't forget to include the jQuery library.

counts = {};
 
      function format_number(text){
          return text.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
      };
       
      function magic_number(element_name, value) {
          var elem = $(element_name);
          var current = counts[element_name] || 0;
          $({count: current}).animate({count: value}, {
                                      duration: 500,
                                      step: function() {
                                          elem.text(format_number(String(parseInt(this.count))));
                                      }});
                                      counts[element_name] = value;
      };
 
      function update() {
          var jqxhr = $.getJSON("number.php?jsonp=?", function(data) {
                               
                              magic_number("#number1", data[0]['n1']);
                              magic_number("#number2", data[0]['n2']);
                     });
      };
 
      setInterval(update, 4000);
      update();

The PHP

For example, number.php generates random numbers and returns them as a JSON object.  add as many numbers to the feed as you like, even retrieving data from a database, simply add extra values to the array below as shown commented out.


$total_data = array(
    array(
        'total' => rand(0,99999999),
        'twitter' => rand(0,99999999)
               // , 'dummy-entry' => $var
     ),
); 
echo $_GET['jsonp'].'('. json_encode($total_data) . ')';

Share this post

pushpam abhishek

About pushpam abhishek

Pushpam Abhishek is a Software & web developer and designer who specializes in back-end as well as front-end development. If you'd like to connect with him, follow him on Twitter as @pushpambhshk

Comments