Caption your JQuery Sliders
I recently had a client who wanted a rating scale control on their site. The perfect choice was the JQuery Slider control. I found this very useful, however I was surprised to realise that it does not support value captions. That is, display some kind of indicator to show the selected value of the slider when it changes.
So, I looked around on the web and found a few people who had some ideas. So I decided to use the best of all suggestions and write my own approach.
Firstly, let's see what the slider looks like.
Rating 1 | Rating 2 | |
---|---|---|
Section 1 | ||
Section 2 |
That code looks like this - StevenWoolston on CodePen.
So, we have a table with sliders inside. The slider won't work yet because we need to configure the div with the class of ui_slider to be a JQuery slider. We do this with javascript. I have commented the code so you can see the logic behind each line.
$(function () {
// create the tooltip element that will appear onChange. Then hide it
var tooltip = $("
").hide();
var sliderid;
// create an array of values. Be sure to size the array appropriately to match the <em>max</em> attribute of your slider
// this is a textual array
var arrCompText = ["Rating 1", "Rating 2", "Rating 3", "Rating 4"];
// this is a numeric array
// var arrCompText = [1, 2, 3, 4, 5];
// initialise the slider
$(".ui_slider").slider({
value: 2,
min: 0,
max: 3,
step: 1,
slide: function (event, ui) {
// this code will fire when the ui-handle is moved
// get the elementID of the slider we are moving
sliderid = $(this).attr("id");
// set the text attribute of the tooltip element we created earlier to be that of the slider value
$("#" + sliderid + " #tooltip").text(arrCompText[ui.value]);
},
change: function (event, ui) {
// this code handles the show/hide functionality
// you could remove the .fadeOut("slow") method if you want the tooltip to stay there after
// it has been changed. This is actually quite a good practice.
$("#" + sliderid + " #tooltip").fadeIn('fast').delay(5000).fadeOut("slow");
}
// append the tooltip in the correct position relative to the handle position
}).find(".ui-slider-handle").append(tooltip);
});
Now we have a slider and a "tooltip" element that displays whenever we move it. So let's include some CSS to style the tooltip element (created inside the javascript block above).
#tooltip
{
position: absolute;
top: -25px;
left: -10px;
height: 25px;
width: 320px;
background: #6bc6b7;
color: #ffffff;
font-size: 0.8em;
font-family: comic sans, Arial, Sans-Serif;
padding: 5px 0px 0px 6px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
border-radius: 10px;
border: 1px solid #d3d3d3;
}
That's it. A nicely formatted slider that gives the user feedback based on the slider position.
Til next time...