Skip to content

Instantly share code, notes, and snippets.

@florentsorel
Created September 9, 2013 10:08
Show Gist options
  • Save florentsorel/6493756 to your computer and use it in GitHub Desktop.
Save florentsorel/6493756 to your computer and use it in GitHub Desktop.
Slider JqueryUI
$.fn.sliderLabel = function(options) {
var settings = $.extend({
marginTop: 2,
// Margin between the slider handle and the label (in pixels)
callback: function(value) {
return 'Value: ' + value;
}
}, options);
return this.each(function() { // <- maintains chainability
var slider = $(this);
var handle = slider.children('.ui-slider-handle');
var data = slider.data('sliderLabel');
if (handle.length === 0) {
// $(this) isn't a slider (it has no handle)
console.log('[SliderLabel] Error: sliderLabel() can only be called on a slider.');
return;
}
if (data === undefined) {
// First time sliderLabel() is called on this slider
data = {
label: $('<div class="ui-slider-label" />').css('position', 'absolute'),
callback: settings.callback
};
data.label.insertAfter(slider);
function updateLabel() {
var value = slider.slider('value');
var labelText = data.callback(value);
data.label.html(labelText);
data.label.css('top', handle.offset().top + handle.outerHeight() + settings.marginTop);
data.label.css('left', handle.offset().left - ((data.label.width() - handle.width()) / 2));
}
updateLabel();
slider.bind('slide', updateLabel);
} else {
// sliderLabel() was called before; just update the callback:
data.callback = settings.callback;
updateLabel();
}
// Save (or update) the data inside the slider:
slider.data('sliderLabel', data);
});
}
$("#slider").slider();
$("#slider").sliderLabel({
callback: function(value) {
return value + '%';
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment