jQuery UI: Slider with mouse scrolling tutorial

If you haven't discovered already, jQueryUI allows you to use jQuery in a way which recreates several very useful user interface elements. It also provides additional animation effects to make life easier.

You'll need:

One of which is the slider, which works quite well when dragging the bar but lacks a bit of support for mouse scrolling over the actual element being scrolled.

image

Now the slider will work as normal. When the slider is dragged, the content will scroll accordingly.

To set up the slider:

$(document).ready(function() {
//scrollpane parts
var scrollPane = $('#scroll-pane');
var scrollContent = $('#scroll-content');

//build slider
var slide_handler = function(e, ui) {

if (scrollContent.height() > scrollPane.height()) {
scrollContent.css('margin-top', Math.round(((100 - ui.value) / 100) * (scrollPane.height() - scrollContent.height())) + 'px');
}
else {
scrollContent.css('margin-top', 0);
}
};

var scrollbar = $("#scroll-bar").slider({
orientation: "vertical",
value: 100, // Sets the value to the top
slide: slide_handler
});
});

This will set up the scrollbar, but when you scroll the mouse over the panel it wont register the events. This is because you'll need to set up the mouse-wheel extension.

Within the document ready event, add:

scrollPane.mousewheel(function(event, delta) {
var value = scrollbar.slider('option', 'value');

if (delta > 0) { value += 10; }
else if (delta < 0) { value -= 10; }

// Ensure that its limited between 0 and 100
value = Math.max(0, Math.min(100, value));
scrollbar.slider('option', 'value', value);
event.preventDefault();
});

This will change the slider value, depending on whether you scrolled up or down.

Infuriatingly, the change in slider value will not update the scrolling panel. This took me a while to figure out, but you'll also have to add another event handler called the "change" event.

You can simply reuse the handler when initialising the slider:

var scrollbar = $("#scroll-bar").slider({
orientation: "vertical",
value: 100,
slide: slide_handler,
change: slide_handler
});

Now when you scroll your mouse over the scroll pane, it'll also change the value of the slider. When the "change" event is triggered, it'll scroll the content.

[ Slider documentation ]

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog