lisburnite lisburnite - 5 months ago 67
Javascript Question

Styling for jQuery UI Slider before handle

I have a requirement to create a slider control as follows:

slider

I'm using jQuery UI Slider to achieve this and have it working to a point where I'm not sure how to style the blue bar before the handle.

This is how mine is looking now

slider

Here is the rendered HTML to produce this slider:

<div id="slider" class="ui-slider ui-slider-horizontal ui-widget ui-widget-content ui-corner-all">
<span class="ui-slider-handle ui-state-default ui-corner-all" tabindex="0" style="left: 45.4545%;"></span>
</div>


I'm guessing I should be using a one of the rendered classes to display the blue bar but not sure how to achieve this.

T J T J
Answer

I've updated the color picker demo to make the range bar look like what you have, using the below CSS:

.ui-slider-range {
  height: 2px !important;
  top: 6px !important;
  margin-left: 2px;
}

function hexFromRGB(r, g, b) {
  var hex = [
    r.toString(16),
    g.toString(16),
    b.toString(16)
  ];
  $.each(hex, function(nr, val) {
    if (val.length === 1) {
      hex[nr] = "0" + val;
    }
  });
  return hex.join("").toUpperCase();
}

function refreshSwatch() {
  var red = $("#red").slider("value"),
    green = $("#green").slider("value"),
    blue = $("#blue").slider("value"),
    hex = hexFromRGB(red, green, blue);
  $("#swatch").css("background-color", "#" + hex);
}
$(function() {
  $("#red, #green, #blue").slider({
    orientation: "horizontal",
    range: "min",
    max: 255,
    value: 127,
    slide: refreshSwatch,
    change: refreshSwatch
  });
  $("#red").slider("value", 255);
  $("#green").slider("value", 140);
  $("#blue").slider("value", 60);
});
#red,
#green,
#blue {
  float: left;
  clear: left;
  width: 300px;
  margin: 15px;
}
#swatch {
  width: 120px;
  height: 100px;
  margin-top: 18px;
  margin-left: 350px;
  background-image: none;
}
#red .ui-slider-range {
  background: #ef2929;
}
#red .ui-slider-handle {
  border-color: #ef2929;
}
#green .ui-slider-range {
  background: #8ae234;
}
#green .ui-slider-handle {
  border-color: #8ae234;
}
#blue .ui-slider-range {
  background: #729fcf;
}
#blue .ui-slider-handle {
  border-color: #729fcf;
}
.ui-slider-range {
  height: 2px !important;
  top: 6px !important;
  margin-left: 2px;
}
<link href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p class="ui-state-default ui-corner-all ui-helper-clearfix" style="padding:4px;">
  <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span>
  Simple Colorpicker
</p>

<div id="red"></div>
<div id="green"></div>
<div id="blue"></div>

<div id="swatch" class="ui-widget-content ui-corner-all"></div>