Triggering onclick event using middle click
Asked Answered
M

8

121

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?

Mozzarella answered 25/11, 2009 at 9:33 Comment(2)
I still don't understand how the problem was solved, when middle click does not trigger the onclick event.Apologize
@TomášZato Browsers don't fire a 'click' event with a middle-click, but they might fire a 'mouseup' event. Then the javascript framework may bind this to a 'click' action to confuse you. I recommend the reading of unixpapa.com/js/mouse.htmlBetthezul
G
73

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.

Graft answered 26/11, 2009 at 14:9 Comment(11)
Keep in mind that .live was deprecated and removed in favor of .onWaldos
To get this working in FF use: var evt = e || window.event;Blotchy
For me FF works only with mousedown event. Click event calls this thing scr.hu/1kig/su5c9Anglocatholic
Is there any cross-browser constant for that 2?Fizzy
@Fizzy there is a standard, but ofc IE doesn't follow it - middle button has id=4, and right button has id=2. Read about it here and here. Check if libraries you use normalize those IDs.Ringlet
@xcy7e웃 - it's not working for me. What is working, though, is changing the eventhandler to either 'mousedown' or 'mouseup'. Tested with FF, Chrome and Edge: Left click: e.which -> 1; e.button: 0 Middle click: e.which -> 2; e.button: 1 Right click: e.which -> 3; e.button: 2 ======= IE8: 1/1; 2/4; 3/2Irritant
This no longer works in Chrome 55. See 1, 2 and this questionAcord
How is this a solution when the problem was that middle click does not trigger the click event to begin with?Autogiro
.which is deprecated, use .button Not sure who named it "which" in the first place. I don't know what web devs were doing 10-15 years ago...Aegeus
LET IT CROSS-BROWSERS: ...function(e) { e = e || window.event; var b = e.keyCode || e.which; if (b == '2') {...Perfidy
This answer should not be pinned to the top as it is out-of-date and it doesn't work.Johannesburg
F
65

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.

Furfural answered 13/3, 2018 at 11:44 Comment(5)
note: onauxclick will work but it does not open the link in a new tab...Knighterrant
This is the only answer that actually works in Chrome. If you need a "click" event for the right mouse button, you can use "contextmenu" (although it's not only fired by right click): developer.mozilla.org/en-US/docs/Web/API/Element/…Bertha
combining with above answer, you can prevent right click capture by if(event.button==1) clause, this is the only working answer.Parve
Note that you need to use both the auxclick event, and to check for the value of e.button == 1. I edited the answer.Johannesburg
Note that it does not work on Safari. caniuse.com/auxclickPrivilege
G
29

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>
Goop answered 25/11, 2009 at 9:45 Comment(5)
I'd recommend using event.which as it has been standardized across browsers in the jQuery source - line 2756 - if ( !event.which && event.button ) event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));Hesperidium
@RussCam However, MouseEvent.which is not defined in any spec, but MouseEvent.button is defined in DOM L2 Events.Hospitable
@Hospitable correct, but implemented differently across different browser vendors. The OP tagged the question with jQuery, so that's why I suggested using event.which but should have elaborated that MouseEvent.which is not part of the official specification.Hesperidium
@rahul, What about gaming mouses with more than 7 buttons? egg-tech.com/blog/images/mouse%20buttons.jpgSpermatozoid
Actually, this doesn't work in browsers like Firefox or Chrome, only for primary click. See 1, 2 and this question.Johannesburg
R
13

This question is a bit old, but i found a solution:

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

Chrome not fire "click" event for the mouse wheel

Work in FF and Chrome

Rhesus answered 11/11, 2015 at 7:40 Comment(2)
I don't want to assume your use case, but I would bet money a lot of people would actually need the 'mouseup' event instead. It works with the middle mouse button as well.Aegeus
When I try this in Firefox and Chrome, it does not prevent the default behaviour of opening the link in a new tab, even though e.preventDefault() is called.Johannesburg
H
8

I usually hate when people offer alternatives instead of solutions, but since solutions have already been provided I'm going to break my own rule.

Websites where the middle-click feature is overridden tend to really, really bug me. I'm usually middle-clicking because I want to open the new content in a new tab while having an unobstructed view of the current content. Any time you can leave the middle-click functionality alone and make the relevant content available through the HREF attribute of your clicked element, I strongly believe that's what you should do.

Han answered 1/8, 2016 at 15:58 Comment(1)
but what if you have tabs on your webpage and want the same behaviour as in your browser? middleclick should close an existing tab then.Tannatannage
S
7

jQuery provides a .which attribute on the event that gives the click button id from left to right as 1, 2, 3. In this case you want 2.

Usage:

$("#foo").live('click', function(e) { 
   if( e.which == 2 ) {
      alert("middle button"); 
   }
}); 

Adamantium's answer will also work but you need to watch out for IE as he notes:

$("#foo").live('click', function(e) { 
   if((!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 2)) { 
     alert("middle button"); 
   } 
});

Also remember the .button attribute is 0-indexed not 1-indexed like .which.

Seiber answered 25/11, 2009 at 10:0 Comment(3)
can i override the functionality of mozilla browser!! eg on left click it opens a pop up.... but for middle click it is not opening a pop up and a new tab is opened in which the pop up is not opening.. so i want to override a middle click functionality of mozilla....Mozzarella
Mozilla has a setting to open all popups in a new tab rather than a new window. If the user has this option enabled then I don't think there is anything you can do. If this is not what is happening can you post some code or a link to the problem page?Seiber
This doesn't work in browsers like Firefox and Chrome.Johannesburg
W
5

The proper method is to use .on, as .live has been deprecated and then removed from jQuery:

$("#foo").on('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

Or if you want the "live" like feel and #foo is not on your page on document start:

$(document).on('click', '#foo', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

original answer

Waldos answered 16/7, 2013 at 15:30 Comment(6)
The event click does not work for the middle mouse button in browsers like Firefox and Chrome.Johannesburg
it used to @JohannesburgWaldos
Yeah. Stack Overflow does not have a good solution for out-of-date answers. I am afraid I have to downvote because "This answer is not useful" any more. What is worse is that the pinned answer can have hundreds or thousands of downvotes because it is out-of-date, and it will still stay pinned forever if the OP is not responding.Johannesburg
Ask a new question :-) (reference this one saying it is out of date and you want a 2020 answer) . But also can use mousedown/mouseup events maybe?Waldos
Even if I do that, people like me are still going to come across this answer when coming from search engines, and are going to be confused by the pinned wrong answer.Johannesburg
I can link it in my answer when you have yours (for a as of 2020 go here or something like that :-) )Waldos
E
3

I know I'm late for the party, but for those still having problems with handling the middle click, check if you delegate the event. In case of delegation, the click event does not fire. Compare:

This works for middle clicks:

$('a').on('click', function(){
  console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="http://example.com">middle click me</a>

This doesn't work for middle clicks:

$('div').on('click', 'a', function(){
  alert('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a href="http://example.com">middle click here</a>
</div>

If you still need to track the middle click using event delegation, the only way around as stated in the corresponding jQuery ticket, is to use mousedown or mouseup instead. Like so:

This works for delegated middle clicks:

$('div').on('mouseup', 'a', function(){
  console.log('middle click');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <a href="http://example.com">middle click me</a>
</div>

See it online here.

Endogenous answered 2/10, 2015 at 11:51 Comment(1)
Actually, click does not work for middle clicks as in your first example.Johannesburg

© 2022 - 2024 — McMap. All rights reserved.