1
votes

I want to excute some function after the user double clicks their mouse wheel. But I can't trigger the event listener when I double click the mouse wheel and code like this doesn't work as I expected:

https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event

const card = document.querySelector('aside');

card.addEventListener('dblclick', function (e) {
  card.classList.toggle('large');
});

This event only triggered when the primary bnutton is clicked. I am not sure this event should be triggered only when the left button is clicked, or when any button is clicked. Can anyone explain this to me?

1

1 Answers

0
votes

Here, you can use MouseEvent.button

MouesEvent has the following numerical representations:

0: Main button pressed, usually the left button or the un-initialized state
1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
2: Secondary button pressed, usually the right button
3: Fourth button, typically the Browser Back button
4: Fifth button, typically the Browser Forward button

document.getElementById('aside').addEventListener('dblclick', function(e) {
  console.log(e.button);
  e.preventDefault();
});

Another example if you use jQuery. jQuery has the event.which attribute, which like the MouseEvent, assigns the following numerical representations:

event.which also normalizes button presses (mousedown and mouseupevents), 
reporting 1 for left button, 2 for middle, and 3 for right. 
Use event.which instead of event.button.

$(".aside").live('dblclick', function(e) { 
   if( e.which == 2 ) {
      alert("middle button"); 
   }
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>