Search code examples
jqueryjquery-knob

jQuery knob stop at max value


I am using jQuery knob with option data-displayPrevious=true.

I need a little change in behavior:

If user changes value up it should stop at maximum value and not jump to minimum after overflow maximum. And if user change value down it should stop at minimum. Exactly like this: http://demo.tutorialzine.com/2011/11/pretty-switches-css3-jquery/

Can you help me with this, please?


Solution

  • This is a crude example of an approach you could do. http://jsfiddle.net/KjtSP/

    It has some issues, like not continuing the drag if you go back, but other than that it should serve as a pretty good basis for you concept. Basically what I'm doing is checking the value that the knob wants to set before it does, and if it fits in the criteria of being either over the maximum or below the minimum so to speak, I cancel the current mouse-event.

    By returning false we prevent the plugin from setting the value it received.

    var knob = $(".dial");
    lastValue = 0;
    max = 100;
    min = 0;
    variance = Math.floor(max / 5);
    
    knob.knob({
        "change": function(v) {
            if (v > max - variance && lastValue < min + variance) {
                knob.val(0).change();
                return false;
            } else if (v < min + variance && lastValue > max - variance) {
                knob.val(100).change();
                return false;
            }
            lastValue = v;
        }
    });​
    

    Update

    Since returning false does prevent the setting of the new value, what you could do is not call the mouseup ergo allowing the continuation of the process. A little tweak of my code, resulting in the following fiddle, allows you to do what you wanted.

    The only quirk you encounter with this code is that if you go over the tolerance or threshold set in the code, your knob will go to that value, but personally I believe that's how it should work.