Change mouse keycode - jquery

menislici picture menislici · Jul 11, 2012 · Viewed 11.1k times · Source

As I have heard, different browsers assign different keycode values to mouse buttons on mousedown event. I have tried this in Chrome and it worked:

$('a').mousedown(function(f) {
    if (f.which == 2) {
        alert("You clicked the wheel")
    }
})​

However, I'm afraid some browsers will fail to recognize the mousewheel's keycode being 2 and will confuse it with the other mouse buttons, thus crashing the code. My question is if there is any way to reset these values so I can use the new ones I provide so all the browsers will know what the numbers represent exactly.

Answer

The Alpha picture The Alpha · Jul 11, 2012

According to W3C its values should be:

  • Left button – 0
  • Middle button – 1
  • Right button – 2

According to Microsoft its values should be:

  • Left button – 1
  • Middle button – 4
  • Right button – 2

But you don't have to think about it (cross browser issue), leave it on jQuery, in every browser which will return the same result

$('a').mousedown(function(e) {
    if( (e.which == 1) ) {
        alert("left button");
    }if( (e.which == 3) ) {
        alert("right button");
    }else if( (e.which == 2) ) {
        alert("middle button"); 
    }
})​;

DEMO. (Tested in IE, Chrome and FF)