4

I need really fast answer. How to distinguish between left and right click inside a function. Code looks like this:

<p onclick="FuncOnClick()">
function FuncOnClick() {
//how to do distinguish?
}
Biffen
  • 6,249
  • 6
  • 28
  • 36
bambi
  • 1,159
  • 2
  • 14
  • 31
  • 2
    possible duplicate of [How can I capture the right-click event in JavaScript?](http://stackoverflow.com/questions/4235426/how-can-i-capture-the-right-click-event-in-javascript) – Henrik Andersson May 18 '15 at 11:12

2 Answers2

4

You can do it like this. Using the HTML onclick does not work for right click. But adding the event listener in Javascript instead does seem to work.

document.getElementById('click').onmousedown = FuncOnClick;

function FuncOnClick(event) {
  console.log(event.which);
  switch (event.which) {
    case 1:
      alert('Left');
      break;
    case 3:
      alert('Right');
      break;
  }
}
<p id="click">test</p>
Thomas Theunen
  • 1,244
  • 9
  • 13
2

You can do like this :-

    $('#mouseClick').mousedown(function(event) {
      switch (event.which) {
        case 1:
          alert('Left Mouse button pressed.');
          break;
        case 2:
          alert('Middle Mouse button pressed.');
          break;
        case 3:
          alert('Right Mouse button pressed.');
          break;
        default:
          alert('You have a strange Mouse!');
      }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="mouseClick">Click here</p>
Alexis Paques
  • 1,885
  • 15
  • 29
NaveenG
  • 292
  • 3
  • 11