Martin Thoma Martin Thoma - 4 years ago 122
Javascript Question

How can get a scroll event work in Chrome and Firefox?

I currently have this piece of code:

canvas.onmousewheel = scroll;

function scroll(event) {
var mousex = event.clientX - canvas.offsetLeft;
var mousey = event.clientY - canvas.offsetTop;
var wheel = parseInt(event.wheelDelta, 10) / 120; //n or -n

var zoom = 1 + wheel / 2;

[... do some action on canvas ...]

Sadly, this doesn't work in Firefox. According to MDN:

Gecko doesn't have a plan to implement this event due to legacy event
type and non-standard.

How can I get my code work for Chrome and Firefox?

edit: The full code is here (one file, about 550 LOC)

Answer Source

You can try the following link

From the page: onmousewheel event and Firefox's equivalent

var mousewheelevt=(/Firefox/i.test(navigator.userAgent))? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x

if (document.attachEvent) //if IE (and Opera depending on user setting)
    document.attachEvent("on"+mousewheelevt, function(e){alert('Mouse wheel movement detected!')})
else if (document.addEventListener) //WC3 browsers
    document.addEventListener(mousewheelevt, function(e){alert('Mouse wheel movement detected!')}, false)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download