Search code examples
javascriptjqueryjquery-knob

jQuery knob animate - how to stop going all the way to maximum value


I have the following code which works great - however I need the animation to stop at the value, not the max value. At present it goes all the way to max value and does not stop at the value of the knob. Any ideas?

jQuery(document).ready(function($) {
    $('.dial').val(0).trigger('change').delay(0);
var myColor = 'red';  
    $(".dial").knob({
    'min':0,
    'max':100,
    'readOnly': true,
    'width': 120,
    'height': 120,
    'fgColor': '#333',
    'dynamicDraw': true,
    'thickness': 0.2,
    'tickColorizeValues': true,
    'skin':'tron'
})
        var tmr = self.setInterval(function(){myDelay()},50);        
        var m = 0;       
        function myDelay(){
            m += 1;
            switch(m)
            {
            case 40:
                  myColor = 'yellow';
              break;
            case 70:
                  myColor = 'green';
              break;                    
            case 100:
              window.clearInterval(tmr);
              break;
            }            
            $('.dial').trigger('configure', {'fgColor':myColor}); 
            $('.dial').val(m).trigger('change');
        }               
});

Solution

  • You can store the atrting value in a variabile in document.ready.

    Then you can check the value in your interval function and if its value is bigger than starting value, stop update the control.

    Code:

    var maxVal = 0;
    jQuery(document).ready(function ($) {
        maxVal = $('.dial').val();
        $('.dial').val(0).trigger('change').delay(0);
        var myColor = 'red';
        var knob = $(".dial").knob({
            'min': 0,
                'max': 100,
                'readOnly': true,
                'width': 120,
                'height': 120,
                'fgColor': '#333',
                'dynamicDraw': true,
                'thickness': 0.2,
                'tickColorizeValues': true,
                'skin': 'tron'
        });
        var tmr = self.setInterval(function () {
            myDelay();
        }, 50);
        var m = 0;
    
        function myDelay() {
            m += 1;
            if (m > maxVal) {
                window.clearInterval(tmr);
                return;
            }
            switch (m) {
                case 40:
                    myColor = 'yellow';
                    break;
                case 70:
                    myColor = 'green';
                    break;
                case 100:
                    window.clearInterval(tmr);
                    break;
            }
            $('.dial').trigger('configure', {
                'fgColor': myColor
            });
            $('.dial').val(m).trigger('change');
        }
    });
    

    Demo: http://jsfiddle.net/IrvinDominin/uHkN5/