I have a page that has multiple sliders (from http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div) and since each of them are different divs I just duplicated the code and changed it to unique classes, which bring this code:
$(document).ready(function(){
$(".slider1").slider({
animate: true,
handle: ".handle1",
change: handleSliderChange1,
slide: handleSliderSlide1
});
$(".slider2").slider({
animate: true,
handle: ".handle2",
change: handleSliderChange2,
slide: handleSliderSlide2
});
$(".slider3").slider({
animate: true,
handle: ".handle3",
change: handleSliderChange3,
slide: handleSliderSlide3
});
});
function handleSliderChange1(e, ui)
{
var maxScroll = $(".gal1").attr("scrollWidth") - $(".gal1").width();
$(".gal1").animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
}
function handleSliderSlide1(e, ui)
{
var maxScroll = $(".gal1").attr("scrollWidth") - $(".gal1").width();
$(".gal1").attr({scrollLeft: ui.value * (maxScroll / 100) });
}
function handleSliderChange2(e, ui)
{
var maxScroll = $(".gal2").attr("scrollWidth") - $(".gal2").width();
$(".gal2").animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
}
function handleSliderSlide2(e, ui)
{
var maxScroll = $(".gal2").attr("scrollWidth") - $(".gal2").width();
$(".gal2").attr({scrollLeft: ui.value * (maxScroll / 100) });
}
function handleSliderChange3(e, ui)
{
var maxScroll = $(".gal3").attr("scrollWidth") - $(".gal3").width();
$(".gal3").animate({scrollLeft: ui.value * (maxScroll / 100) }, 1000);
}
function handleSliderSlide3(e, ui)
{
var maxScroll = $(".gal3").attr("scrollWidth") - $(".gal3").width();
$(".gal3").attr({scrollLeft: ui.value * (maxScroll / 100) });
}
While this works just fine too, I have about 7 of these slides (only 3 are shown above) and I feel kinda bad about repeating basically the same code…
could there be a way to simplify this code?
It looks like that slider demo is quite old and the slider is one of the jQuery UI widgets. It looks like the side-scroll jQuery UI slider demo most closely matches the demo page linked in your question.
I had a play around to see if I could mimic the old demo page in the jQuery UI and came up with this demo. Not sure if it’s what you are after though.