Mouse Event Button


/ Published in: JavaScript
Save to your folder(s)

Returns an object with the `event.button` values of both the W3C and Microsoft models.


Copy this code and paste it in your HTML
  1. //returns event.button in both the W3C and Microsoft models
  2. //in IE lte 8, a button combination (like 3==left+right) returns -1
  3. function button(evt)
  4. {
  5. evt = evt || window.event;
  6. var ms, w3c;
  7.  
  8. //in the W3C model, 0==left, 1==middle, 2==right
  9. //in the Microsoft model, 1==left, 4==middle, 2==right
  10.  
  11. if(evt.which)
  12. {
  13. w3c = evt.which - 1;
  14. ms = evt.which == 1 ? 1 /*left*/ : evt.which == 2 ? 4 /*middle*/ : 2 /*right*/;
  15. }
  16. else //IE lte 8
  17. {
  18. ms = evt.button; //actually, this would need to be: evt.button & !previous_evt_button
  19. //otherwise, if evt.button == 3 (for example), it could be either the left or the right button
  20. //since we can't reliably keep track of the previous evt.button, we will use -1 for the w3c value
  21. // if ms is not 1, 4, or 2
  22. w3c = ms == 1 ? 0 /*left*/ : ms == 4 ? 1 /*middle*/ : ms == 2 ? 2 /*right*/ : -1 /*unknown*/;
  23. }
  24.  
  25. return {w3c: w3c, ms: ms};
  26. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.