user3650556 user3650556 - 5 months ago 40
jQuery Question

jQuery to animate changing value of input field

I have the following jsfiddle: http://jsfiddle.net/60oa2zah/

//Add Value to slider button
$("[data-slider]")
.each(function () {
var input = $(this);
})
.bind("slider:ready slider:changed", function (event, data) {
$(".dragger")
.html('<span>$' + addCommas(data.value.toFixed(0)) + '</span>');
});
//Add thousands separator
function addCommas(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}


When loading the page, I would like the slider to animate from a start value of $100 to an end value of $500. I've tried animating the value field, but haven't had any luck. Is there another way to accomplish this? On page load, the slider should appear to drag itself to $500.

This is my attempt to animate the slider (doesn't work...)

//Drag from 100 to 500
$(document).ready(function() {
$("#Amount").val(
$({countNum: 100}).animate({countNum: 500}, {
duration: 3000,
easing:'linear',
step: function() {
console.log(Math.floor(this.countNum));
}
}); );
});

Answer

You really can use jQuery's .animate() function if you want, and your code was close. (reference)

Two things though:

  1. The value being animated has to start at zero. So you need to have it animate from 0 to 400, rather than from 100 to 500. (See the comment to this answer)
  2. Use selector.simpleSlider("setValue", newValue) to set the value of the slider. (jQuery Simple Slider documentation)

Here's the code:

$(document).ready(function() {
    $({ val: 0 }).animate({ val: 400 }, {
        duration: 3000,
        easing: 'linear',
        step: function(val) {
            $("#Amount").simpleSlider("setValue", 100 + Math.ceil(val));
        }
    });
});

jsfiddle

Instead of using .animate(), you could use setInterval() as follows:

$(document).ready(function() {
    var interval = setInterval(function() {
        var val = +$('#Amount').val() + 100;
        $("#Amount").simpleSlider("setValue", val);
        if (val >= 500) {
            clearInterval(interval);
        }
    }, 750);
});

jsfiddle