Search code examples
jqueryjquery-knob

Formatting value label to fit without being cut off


I've got an issue where i'm automatically formatting my jQuery.Knob instance and it's being cut off incorrectly. It ends up looking like this:

jQuery Knob being cut off enter image description here etc....

This slider just goes up in range (max will be around $10,000,000, potentially more), so you can understand that a larger portion of the displayed value will be cut off as it grows, which isn't what I want....

I managed to counter-act that with overloading the draw method, applying the following, but this isn't a full-proof method of doing so as the font size grows:

$(this.i).css('font-size', '90%').val('$' + parseFloat(this.cv, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());

But, I'd like a cleaner method without having to apply my own CSS to the presented label.

I did try through the format with the following, but it's overloading:

format: function (value) {
    return '$' + parseFloat(value, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
},

DEMO


I am using Bootstrap if that has anything to do with it, and the HTML for this container looks like this below:

<div class='row margin-top-45'>
    <div class='col-lg-4'>
        <input value="50000" class="dial" data-step="5000" data-min="0" data-max="10000000" data-thickness="0.2" data-fgColor="#16A085" data-skin="tron">
    </div>
</div>

Solution

  • Here is my example of dynamically changing the font if you decide to go with this solution: https://jsfiddle.net/3c4d7L53/3/ Try changing the value from xxxxx.xx to xxxxxx.xx and you'll notice font reduce itself. From here you decide what the font value will be based on the number of digits you have to display using basic math.

    Code itself is below. I kept your overloaded format function and added change function:

    jQuery('.dial').knob({
      format: function(e) {
        return '$' + parseFloat(e, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
      },
      change: function(v) {
        var v = parseInt(v);
        var valLength = String(v).length;
        var defaultFontSize = 22;
    
        if (valLength > 5) {
          var defaultFontSize = 22 - ((valLength - 5) * 4);
          this.i.css({
            font: 'bold ' + defaultFontSize + 'px Arial'
          });
        } else {
          this.i.css({
            font: 'bold ' + defaultFontSize + 'px Arial'
          });
        }
    
      }
    });