2

Why preventDefault() on case 3 doesn't work? Browser's menu should not appear on right click.

$('#btnB').on('mousedown', function(e){
 switch (e.which) {
 case 1:
  console.log('left');
  break;
 case 3:
  e.preventDefault();
  console.log('right');
  break;
 default:
  alert('323');
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btnB'>CLICK</button>
qadenza
  • 9,025
  • 18
  • 73
  • 126
  • How do you know that it isn't working? Perhaps you should post your code so that we can test it, as I can't see any problem with the example you've shown here. – Martin Jan 03 '19 at 10:16
  • @MartinParkin, problem is because browser's context menu appears. I posted the code, what's the problem with you? – qadenza Jan 03 '19 at 10:17
  • @Ben I believe it's not really a duplicate of this question. – dfsq Jan 03 '19 at 10:20

3 Answers3

2

Context menu appears because it reacts to different event, not mousedown. Try to listen both mousedown (probably not needed even) and contextmenu events:

 $('#btnB').on('mousedown contextmenu', function(e){
  switch (e.which) {
  case 1:
    console.log('left');
    break;
  case 3:
    e.preventDefault();
    console.log('right');
    break;
  default:
    alert('323');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='btnB'>CLICK</button>
Pingolin
  • 3,161
  • 6
  • 25
  • 40
dfsq
  • 191,768
  • 25
  • 236
  • 258
2

Same as answer of @dfsq, but with catch of double trigger on contextmenu. I cannot edit his answer for some reason and I want to show a demo.

$('#btnB').on('contextmenu mousedown', function(e) {
  switch (e.which) {
    case 1:
      console.log('left');
      break;
    case 3:
      if (e.type !== 'contextmenu') break;
      e.preventDefault();
      console.log('right');
      break;
    default:
      alert('323');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="btnB">HAHAHA</span>
ACD
  • 1,431
  • 1
  • 8
  • 24
  • thanks, it works. Strange - `dfsq's` answer is incorrect and upvoted twice. – qadenza Jan 03 '19 at 10:41
  • @qadenza it is *correct* and the answer here is just an improved version of it. main idea here is listening for `oncontextmenu` event ;) – dfsq Jan 03 '19 at 12:10
1

If you want to prevent the context menu from opening you can do so by listening to the contextmenu event

$('#btnB').on('contextmenu', function(e) {
            alert("hey new menu"); 
            e.preventDefault();
        });
Ced
  • 15,847
  • 14
  • 87
  • 146