Mouse Buttons on different Browsers


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

Deals with the fact that mouse buttons are referenced in different ways by different browsers.


Copy this code and paste it in your HTML
  1. // Browser detection
  2.  
  3. var ie=document.all != null; //ie4
  4. var op7=navigator.userAgent.indexOf("opera")>0 && operaVersion() <= 7;
  5.  
  6. function operaVersion() {
  7. agent = navigator.userAgent;
  8. idx = agent.indexOf("opera");
  9. if (idx>-1) {
  10. return parseInt(agent.subString(idx+6,idx+7));
  11. }
  12. }
  13.  
  14.  
  15. /* Detection of the mouse button
  16.  
  17.   L M R
  18. IE,KON 1 4 2 event.button
  19. NS,OP8,FF 0 1 2 e.button
  20. OP7 1 3 2 e.button
  21. NS,OP8,FF 1 2 3 e.which
  22. */
  23.  
  24. var leftButton = ie? 1 : 0; // op7 supports document.all
  25. var middleButton = op7 ? 3 : ie ? 4 : 1;
  26. var rightButton = 2;
  27.  
  28. document.onmouseup = onClick;
  29.  
  30. // This code is executed each time a mouse button is released
  31. function onClick(e) {
  32. if (ie) {
  33. var elem = event.srcElement;
  34. var btn = event.button;
  35. //e = event;
  36. } else {
  37. var elem = e.target;
  38. var btn = e.button;
  39. }
  40. // elem is the element the user clicked on
  41. // btn is the mouse button which was used
  42. // e.g. if (btn == leftButton) { alert( elem + ": You clicked me!" ); }
  43.  
  44. /* ...your code goes here... */
  45.  
  46. return false;
  47. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.