views:

615

answers:

3

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 pop up.

+1  A: 

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.

rahul
I'd recommend using `event.which` as it has been standardized across browsers in the jQuery source - line 2756 - `if ( !event.which `
Russ Cam
A: 

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.

beggs
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....
TbmBizz
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?
beggs
+3  A: 

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").live('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

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

Gausie