I have found a nice jquery increment script. The increment portion can accept a function or just a regular number. I am looking to increase at a random number between 1 and 100. How would I write the function for this?
$( document ).ready( function()
{
$( '.tick' ).ticker(
{
incremental : 1,
delay : 1500,
separators : true
});
$(".comma-change").html(".");
});
<span class="tick">2,354,456</span>
So rather than increase by 1 in the incremental field, I would like to write a function that updates with a random number. With the help of other posts I can write the function that creates a random number no problem:
function random_generator (min, max) {
return Math.random() * (max - min) + min;
}
but I am having trouble working it into this directly.
Here is the increment portion of the plugin:
Tick = (function() {
function Tick(element, options) {
this.element = element;
if (options == null) options = {};
this.running = false;
this.options = {
delay: options.delay || 1000,
separators: options.separators != null ? options.separators : false,
autostart: options.autostart != null ? options.autostart : true
};
this.increment = this.build_increment_callback(options.incremental);
this.value = Number(this.element.html().replace(/[^\d.]/g, ''));
this.separators = this.element.html().trim().split(/[\d]/i);
this.element.addClass('tick-active');
if (this.options.autostart) this.start();
}
Tick.prototype.build_increment_callback = function(option) {
if ((option != null) && {}.toString.call(option) === '[object Function]') {
return option;
} else if (typeof option === 'number') {
return function(val) {
return val + option;
};
} else {
return function(val) {
return val + 1;
};
}
};
and then this bit:
Tick.prototype.tick = function() {
this.value = this.increment(this.value);
this.render();
return this.set_timer();
};
All you need to do is translate your function statement into a function expression. A function statement defines a name and assigns it a function whereas a function expression is the function itself (an anonymous function).
You can set the value of a variable to a function like this
and then pass the reference to this function (the variable random_generator) as the incremental to your plugin. Or you could inline the function definition like this:
edit: I didn’t realize, that your function has two parameters… that makes the whole thing a little bit more sophisticated. You could either hardcode min and max into your function (because the function gets invoked by code from the plugin and you will most definitely not get any arguments), or wrap another anonymous function around it, that provides the two parameters for us.
Final edit: I guess you are using this plugin https://github.com/harvesthq/tick ? This plugin can accept a function that will be called every tick and gets passed in the current value of the ticker. You have to provide the new value. I updated the code snippet accordingly.