2

I have this animated donut that changes value on li hover. However, currently it resets to 0 and then animates to the new value. Ideally it should animated from value to value.

Here's a JSFiddle: http://jsfiddle.net/jme11/xx2Ky/

My JS:

var dial = $('.dial');
dial.knob({
    readOnly: true
});
$('.pets > li').on('mouseenter', function () {
    var button = $(this);
    var myVal = button.data('value');
    button.css('backgroundColor', 'yellowgreen').siblings().css('backgroundColor', '#ccc');
    dial.stop().animate({
        value: myVal
    }, {
        duration: 200,
        easing: 'swing',
        step: function () {
            dial.val(Math.ceil(this.value)).trigger('change');
        },
        complete: function () {
            dial.val(myVal + '%');
        }
    });
});
univers_
  • 463
  • 1
  • 4
  • 14
  • As a sidenote, I noticed that you *do* get your desired behavior if you mouse back and forth very quickly so the animation doesn't have time to stop. So I'd say you're very close; `dial.stop().animate({` jumps out at me as possibly being incorrect. – Andrew Aug 01 '14 at 15:18
  • I noticed this too but my JS knowledge is not good enough to troubleshoot. The problem is probably that I want the animation to stop on mouseout, otherwise it keeps going and looks awkward. But it also needs to jump from value to value. @AndrewArnold – univers_ Aug 01 '14 at 15:26

1 Answers1

2

I have located the problem; it's this:

dial.val(myVal + '%');

When you animate something with a val attribute, it automatically uses that val value as its starting point. However, your code is setting val to a string. jQuery then gets confused and defaults to 0 the next time you want to animate. If you change the line to

dial.val(myVal);

you'll see it works as desired—with the obvious drawback that you lose your percent sign. You can add it back with knob's format feature, seen here, but I can't get it to work in your jsFiddle.

Community
  • 1
  • 1
Andrew
  • 4,953
  • 15
  • 40
  • 58
  • Excellent! Thanks so much. I'm not using the data value anyway, just the knob, so no loss for me. @AndrewArnold – univers_ Aug 01 '14 at 15:34