Slider – part 2 – using a mouse wheel

Last modified date

Comments: 0

Following on from the previous post, I thought it’d be nice to have the handle move on a mouse wheel. Looking around for mouse wheel integration, it seems that it’s only a short amount of code to update Prototype to use the mouse wheel. Why it’s not in the core code I don’t know, as it seems rather handy. The mouse wheel code is listed at the Prototype Event Extension article over at Ajaxian.

I decided to integrate the code directly in to Prototype, also dropping the following in to ‘observe’ and ‘stopObserving’:

[javascript]if (name == ‘mousewheel’ &&
(element.addEventListener))
name = ‘DOMMouseScroll’;[/javascript]

Then using the same XHTML as before, which was:

[html]<div id="slider">
<div id="slider-bar">
<div id="slider-handle"><p id="percent"></p></div>
</div>
</div>[/html]

all you have to do is drop an event on the div#slider for the mouse wheel. That little bit of javscript looks like:

[javascript]Event.observe(‘slider’, ‘mousewheel’, function(e) {
slide.setValueBy((Event.wheel(e)/10));
});[/javascript]

Now when you scroll the mouse wheel the slider will change by a value of 10. This value comes from the ‘Event.wheel(e) / 10’ part. The mouse wheel method returns either 1 or -1, and the slider goes from 0 to 1. Obviously, if you want the mouse wheel to move the slider by only a value or 1, then divide the delta by 100; ‘Event.wheel(e) / 100’.

As before, you can see it in action at http://dev.amnuts.com/slider/.

Share

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.