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.
You can use
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.
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' 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.