Search code examples
javascriptjquerycssjquery-uijquery-ui-slider

jQuery-UI Slider Background


Is it possible to set background color (via JavaScript) of jQuery-UI Slider widget?

This is normal:

normal behavior

What I am looking to achieve is following:

with background

Green range would be calculated based on historical data. I would like to indicate to user what is a "healthy" range.

Thanks in advance for any pointers.


Solution

  • jQuery UI does not offer such a feature, but it is not difficult to implement it.

    $.fn.addRange = function (min, max) {
      this.prepend('<div class=range></div>');
      $range = this.find('.range');
      $range.css("left", min * 100 + '%');
      $range.css("right", 100 - (max * 100) + '%');
    };
    
    var $slider = $('#slider');
    $slider.slider();
    $slider.addRange(0.2, 0.4);
    

    This adds a <div class=range></div> inside the slider and sets its left and right CSS properties to 20% and 40%.

    And the accompanying CSS:

    #slider {
      background-color: red;
      background-image: none;
    }
    
    .range {
      position: absolute;
      top: 0;
      bottom: 0;
      background-color: green;
    }
    

    Result:

    screenshot

    Demo: http://jsbin.com/eheden/1/edit