skip to Main Content

How to listen to pointerUp event from a different mouse button when a mouse button is pressed down?

Im trying to listen to pointerUp event from right mouse button while the left mouse button is held down. For some reason when any mouse button is held down subsequent pointer down events from any other mouse buttons are not triggering pointerUp events, is there a workaround for this issue?

Thanks for the help in advance 🙂

2

Answers


  1. You can do something like this

    Read more here: mdn

    window.addEventListener('mousedown', (e) => {
      switch (e.buttons) {
        case 1:
          console.log('left button down');
          break;
        case 2:
          console.log(`right button down`);
          break;
        case 3:
          if (e.button === 0)
            console.log('left button down while holding right button');
          if (e.button === 2)
            console.log('right button down while holding left button');
          break;
      }
    });
    
    window.addEventListener('mouseup', (e) => {
      switch (e.buttons) {
        case 0:
          if (e.button === 0) console.log('left button up');
          if (e.button === 1) console.log('right button up');
          break;
        case 1:
          console.log('right button up while holding left button');
          break;
        case 2:
          console.log('left button up while holding right button');
          break;
      }
    });
    

    Working sample: https://stackblitz.com/edit/vitejs-vite-rv2qvg?file=main.js&terminal=dev

    Login or Signup to reply.
  2. You should consider disabling the context menu if you want consistent output, if that is applicable to you:

    document.addEventListener('mousedown', function (event) {
        let button;
        if (event.button === 0) button = 'Left';
        else if (event.button === 2) button = 'Right';
        console.log(`Mouse Down: ${button}`);
    });
    
    document.addEventListener('mouseup', function (event) {
        let button;
        if (event.button === 0) button = 'Left';
        else if (event.button === 2) button = 'Right';
        console.log(`Mouse Up: ${button}`);
    });
    
    // disable context menu
    document.addEventListener('contextmenu', function (event) {
        event.preventDefault();
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search