Thursday, December 7, 2006

Prototype Event Extension: Event.wheel(e)

Frank Monnerjahn created a Prototype Event extension which makes it trivial to use the mouse wheel in Prototype with Event.observe(..).
The demo shows this in action.
The Code:

/*
* Orginal: http://adomas.org/javascript-mouse-wheel/
* prototype extension by "Frank Monnerjahn" themonnie @gmail.com
*/

extend(Event, {

wheel:function (event){

var delta = 0;

if (!event) event = window.event;

if (event.wheelDelta) {

delta = event.wheelDelta/120;

if (window.opera) delta = -delta;

} else if (event.detail) { delta = -event.detail/3; }

return Math.round(delta); //Safari Round

}

});

/*

* end of extension

*/

var counterSite=0;

function handleSite(e) {

counterSite += Event.wheel(e);

$('delta').innerHTML = counterSite +'#'+ Event.wheel(e) + ": " + (Event.wheel(e) <0 ? 'down' : 'up' );

}

var counterDIV=0;

function handleDIV(e) {

counterDIV += Event.wheel(e);

$('divdelta').innerHTML = counterDIV +'#'+ Event.wheel(e) + ": " + (Event.wheel(e) <0 ? 'down' : 'up' );

}


Usage:
Event.observe(document, "mousewheel", handleSite, false);

Event.observe(document, "DOMMouseScroll", handleSite, false); // Firefox

Event.observe($('divdelta'), "mousewheel", handleDIV, false);

Event.observe($('divdelta'), "DOMMouseScroll", handleDIV, false); // Firefox

No comments: