I´d like to build a UI Slider to change an Image. So far, I´ve managed that the Image will change manually and automaticly every three Seconds.
I´m not very happy with the code, because when it reaches the max-value and repeats from beginning, it skippes the last value because of the setInterval. Is there an easier and prettier way to solve this?
HTML
<div id="wrapper">
<div class="image">
<img id="image" src="http://fakeimg.pl/350x200/?text=0&font=lobster" />
</div>
<div id="slider"></div>
</div>
Script
$(function () {
$('#slider').slider({
value: 0,
min: 0,
max: 5,
step: 1,
change: function (event, ui) {
var slideruivalue = (ui.value);
image = $('#image');
image.attr('src', 'http://fakeimg.pl/350x200/?text=' + slideruivalue);
if (slideruivalue == $(this).data("slider").options.max) {
$('#slider').slider('value', 0);
}
}
});
$(function AutoSlider() {
setTimeout(function () {
$("#slider").slider("value", $('#slider').slider("value") + 1);
}, 3000);
setTimeout(AutoSlider, 3000);
});
});
In your setTimeout, get the max of your slider, and then calculate the new value with a modulus (operator %) on max+1 :
setInterval(function () {
var value = $('#slider').slider("value");
var max = $('#slider').slider( "option", "max" );
$("#slider").slider("value", (value + 1)% (max+1));
}, 3000);
Then, there is no need to check the value in the change callback :)
You can also use setInterval instead of two setTimeout
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments