JSFiddle - React, Tailwind, and code Playground
by Rusln
HTML
<div id="dragSlider"></div>
<select id="select">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="4">Option4</option>
<option value="5">Option5</option>
</select>
JavaScript
// custom slider widget with a draggable handle
$.widget("ui.dragSlider", $.ui.slider, {
_create: function () {
var that = this;
this._super('_create');
// get the width of the slider
var drWidth = that.element.context.clientWidth;
// get the maximum value
var drMax = that.options.max;
// calculate the distance between each slider step
var drStep = drWidth / drMax;
// turn the slider handle into a draggable
$(this.handle).draggable({
animate: true,
axis: "x",
containment: "parent",
drag: function (event, ui) {
// trigger slider events from inside the draggable handle
that._trigger("slide",event,ui);
},
stop: function (event, ui) {
// you'll need some better math
// so this handle can react more precise,
// this is just an example of how to pass position
// of our draggable handle to the slider
var value = Math.round(ui.position.left / drStep);
// _setOption will trigger slider's change event
that._setOption("value", value);
// trigger the stop event of the slider
that._trigger("stop","slidestop",ui);
}
});
}
});
// custom implementation
$("#dragSlider").dragSlider({
min: 1,
max: 5,
animate: true,
slide: function (event, ui) {
// slide handler can now be triggered by the drag event handler
},
change: function (event, ui) {
// change the value of select
$("#select").val(ui.value);
}
});
$("#select").change(function (e) {
// change the value of the slider
$("#dragSlider").dragSlider("value", $(this).val());
});