Mouse Event Positions


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



Copy this code and paste it in your HTML
  1. //position values of a mouse event
  2. //usage: var pos = new MousePosition(mouse_event);
  3. function MousePosition(evt)
  4. {
  5. this.screen = {
  6. x: evt.screenX,
  7. y: evt.screenY
  8. };
  9. this.window = this.frame = {
  10. x: evt.clientX,
  11. y: evt.clientY
  12. };
  13.  
  14. if(isNaN(evt.pageX) || isNaN(evt.pageY))
  15. {
  16. //scroll position of document
  17. var left, top;
  18. if(window.pageYOffset) //all except IE
  19. {
  20. left = window.pageXOffset;
  21. top = window.pageYOffset;
  22. }
  23. else if(document.documentElement && !isNaN(document.documentElement.scrollTop)) //IE standards compliance mode
  24. {
  25. left = document.documentElement.scrollLeft;
  26. top = document.documentElement.scrollTop;
  27. }
  28. else //IE quirks mode
  29. {
  30. left = document.body.scrollLeft;
  31. top = document.body.scrollTop;
  32. }
  33.  
  34. this.document = {
  35. x: left + evt.clientX,
  36. y: top + evt.clientY
  37. };
  38. }
  39. else
  40. {
  41. this.document = {
  42. x: evt.pageX,
  43. y: evt.pageY
  44. };
  45. }
  46.  
  47. this.layer = {
  48. x: evt.layerX || evt.x,
  49. y: evt.layerY || evt.y
  50. };
  51. }
  52.  
  53. //returns event.button in both the W3C and Microsoft models
  54. //in IE lte 8, a button combination (like 3==left+right) returns -1 for the W3C model
  55. function mouseButton(evt)
  56. {
  57. var ms, w3c;
  58.  
  59. //in the W3C model, 0==left, 1==middle, 2==right
  60. //in the Microsoft model, 1==left, 4==middle, 2==right
  61.  
  62. if(evt.which)
  63. {
  64. w3c = evt.which - 1;
  65. ms = evt.which == 1 ? 1 /*left*/ : evt.which == 2 ? 4 /*middle*/ : 2 /*right*/;
  66. }
  67. else //IE lte 8
  68. {
  69. ms = evt.button; //actually, this would need to be: evt.button & !previous_evt_button
  70. //otherwise, if evt.button == 3 (for example), it could be either the left or the right button
  71. //since we can't reliably keep track of the previous evt.button, we will use -1 for the w3c value
  72. // if ms is not 1, 4, or 2
  73. w3c = ms == 1 ? 0 /*left*/ : ms == 4 ? 1 /*middle*/ : ms == 2 ? 2 /*right*/ : -1 /*unknown*/;
  74. }
  75.  
  76. return {w3c: w3c, ms: ms};
  77. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.