Chrome: Auxiliary Click Event with Middle Mouse Button not fired if page is scrollable
Asked Answered
A

1

6

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.

Aleman answered 6/9, 2021 at 13:28 Comment(5)
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; }};Jaques
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.Aleman
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 elementJaques
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; }};Jaques
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: codepen.io/nioe/pen/rNwWWZjAleman
A
8

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. ;)

Aleman answered 6/9, 2021 at 14:23 Comment(2)
the return false and preventDefault seems to do the same but return false actually fires multiple things, see here for more infoJaques
i had to preventDefault for both mousedown and mouseup to make it workPasahow

© 2022 - 2024 — McMap. All rights reserved.