I want to create a slider which has some stop points. Whenever I click on any item, I want the slider to jump at that point and do some action. I have created the slider with jQuery UI's slider. It's pretty easy, but I don't exactly know how to add those stop points. Is there a ready-made library for this or should I implement this myself? If so, could you please help me get on track?
I want to create a slider which has some stop points. Whenever I click on any item, I want the slider to jump at that point and do some action. I have created the slider with jQuery UI's slider. It's pretty easy, but I don't exactly know how to add those stop points. Is there a ready-made library for this or should I implement this myself? If so, could you please help me get on track?
Share Improve this question asked Mar 3, 2013 at 21:37 Alireza NooriAlireza Noori 15.3k30 gold badges102 silver badges190 bronze badges 1-
click on any item
... what items? Could putdata
attribute on those items and set slider from that value. Need more detail about what you need exactly. A demo in jsfiddle would help, with enough data to work with – charlietfl Commented Mar 3, 2013 at 21:42
1 Answer
Reset to default 8I did something similar to this before. It's basically working like this:
- I store all possible values in an array (in my case "keyframes" like your "stop points")
- the
stop()
-callback of the slider triggers a function called_getClosest
and sets the new value - a click on the links below the slider let the it jump directly to that position
Demo
http://jsfiddle/eTTM2/
HTML
<div id="slider"></div>
<div id="keyframes">
<a>|</a><a>|</a><a>|</a><a>|</a><a>|</a><a>|</a><a>|</a>
</div>
Slider, links and keyframes
var slider = $('slider');
var links = $('#keyframes > a');
var values = [0, 10, 34, 67, 80, 85, 100];
// initiate slider
slider.slider({
value: 0,
min: 0,
max: 100,
animate: 500,
stop: function( event, ui ) {
slider.slider('value', _getClosest(ui.value) );
}
});
// add click to the links
links.click(function() {
slider.slider('value', values[$(this).index()]);
});
How to get the closest element to slide to
The easiest way is to pare the current slider position to the possible keyframes:
- if I'm already half the way or further I move to the next element
- if I've not reached the middle, I go back to the element before
So _getClosest()
can look like this:
function _getClosest(value) {
var closest = null;
$.each(values, function(_key, _value) {
if (closest == null || Math.abs(this-value) < Math.abs(closest-value)) {
closest = this;
}
});
return closest;
}
Place links below the slider corresponding to their values
To place the links at their respective position, simply loop thru them and set the left offset according to the values from the values
-array. This time I multiplied the value with a factor of 2
because the slider in the demo is 200px
wide but has a range from 0-100
:
$.each(links, function(key, value) {
$(value).css('left', values[key] * 2);
});