Is there a way to enable scroll with the middle mouse button (aka mouse 3) when CTRL (or some other key) were pressed together; instead of the default behavior which is redirection to the href in a new tab?
https://jsfiddle.net/b7zyx39f/
My code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/800"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/800"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
<a href="https://stackoverflow.com/"><img src="https://via.placeholder.com/150"></a>
</body>
</html>
You can prevent the middle click and prevent the default action using the auxevent
(see this). But in your case I suggest to remove the href
of the a
tag and add an attribute data-href
for the link. Then add a on click listener for those a
tags which will redirect to the desired link. An example might be,
<a data-href="https://stackoverflow.com/"><img src="https://via.placeholder.com/800"></a>
and in javascript
document.querySelectorAll("a").forEach(href => {
href.addEventListener("click", e => {
window.location.href = href.dataset.href;
});
});
To capture the ctrl button you may add another event listener for redirecting on middle click if ctrl is not pressed
href.addEventListener("auxclick", e => {
if (!window.event.ctrlKey) {
window.open(href.dataset.href, '_blank');
}
});