Triggering onclick event using middle click

I am using the onclick event of a hashed link to open a <div> as a pop up. But the middle click does not trigger the onclick event but only takes the href attribute value of the link and loads the URL in a new page. How can I use middle click to open the <div> as a popup?


EDIT

This answer has been deprecated and doesn't work on Chrome. You will most probably end up using the auxclick event, but please refer to other answers below.

/EDIT


beggs' answer is correct, but it sounds like you want to prevent the default action of the middle click. In which case, include the following

$("#foo").on('click', function(e) {
   if (e.which == 2) {
      e.preventDefault();
      alert("middle button"); 
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="foo" href="http://example.com">middle click me</a>

preventDefault() will stop the default action of the event.


For the middle-click / mouse-wheel button to be detected, you have to use the event auxclick. E.g:

<a href="https://example.com" onauxclick="func()" id="myLink"></a>

Then in your script file

function func(e) {
  if (e.button == 1) {
    alert("middle button clicked")
  }
}

If you want to do it from JavaScript (without using the HTML attribute onauxclick), then you addEventListener to the element:

let myLink = document.getElementById('myLink')
myLink.addEventListener('auxclick', function(e) {
  if (e.button == 1) {
    alert("middle button clicked")
  }
})
<a id="myLink" href="http://example.com">middle click me</a>

Checkout the mdn page about the auxclick event here.


You can use

event.button

to identify which mouse button was clicked.

Returns an integer value indicating the button that changed state.

  • 0 for standard 'click', usually left button
  • 1 for middle button, usually wheel-click
  • 2 for right button, usually right-click

Note that this convention is not followed in Internet Explorer: see QuirksMode for details.

The order of buttons may be different depending on how the pointing device has been configured.

Also read

Which mouse button has been clicked?

There are two properties for finding out which mouse button has been clicked: which and button. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.

document.getElementById('foo').addEventListener('click', function(e) {
  console.log(e.button);
  e.preventDefault();
});
<a id="foo" href="http://example.com">middle click me</a>