5

I try to detect a middle mouse button click on a HTML Custom Element by adding a listener for the auxclick-Event to it. As long as the page is not scrollable, this works totally fine in Chrome on a Win 10 machine.

As soon as the page is scrollable however, the event is not fired anymore and the standard bahavior of a middle click kicks in (scrolling the page by moving the mouse).

scrolling triggered on middle click

Does anyone know a way to work around this issue?

I've created a small CodePen to demonstrate the behavior. Without scrolling it just works fine, but if you uncomment line 2 in the CSS pane (min-height: 200vh;) the middle click triggers the scrolling behaviour.

nioe
  • 756
  • 1
  • 7
  • 15
  • is disabling the scroll is a valid answer? `document.getElementsByClassName("middle-click")[0].onmousedown = function(e) { if (e.which === 2) { console.log('Disabled'); return false; }};` – iѕєρєня Sep 06 '21 at 13:39
  • Not really. I'm building a component library and don't know on what page these components are used. Therefore I cannot simply disable the scrolling. – nioe Sep 06 '21 at 13:54
  • note that its only disables scrolling by middle click press and only when it happens on your counter element. the scrolling can happen using mouse wheel and using middle mouse button outside that element – iѕєρєня Sep 06 '21 at 13:58
  • OR you can have the scroll and everything and also count the clicks by something like this: `document.getElementsByClassName("middle-click")[0].onmousedown = function(e) { if (e.which === 2) { console.log('Disabled'); const counter = document.querySelector('.counter'); counter.innerText = Number.parseInt(counter.innerText) + 1; }};` – iѕєρєня Sep 06 '21 at 14:02
  • Ah, sorry. Now I got what you meant. Disabling the scrolling didn't do the trick, but when I call `preventDefault()` on the Mouse Down Event, it seems to work: https://codepen.io/nioe/pen/rNwWWZj – nioe Sep 06 '21 at 14:11

1 Answers1

4

Kudos to iѕєρєня for pointing me into the right direction.

If I listen to the mousedown-Event too, check if it has been fired from a middle click and then prevent the default behaviour, everything seems to work fine.

Checkout the updated CodePen for the full solution.

I still think that this is kind of a hack. If somebody knows why Chrome does behave like this, I would be glad, if you'd share it here. ;)

nioe
  • 756
  • 1
  • 7
  • 15
  • the `return false` and `preventDefault` seems to do the same but `return false` actually fires multiple things, [see here for more info](https://stackoverflow.com/a/30473685/4893439) – iѕєρєня Sep 06 '21 at 14:38