I've had this problem recently (actually the opposite: I wanted to only allow middle clicks to get through). The problem is that the behaviour you want to prevent is on the click
, and preventing the default behaviour of mousedown
does not necessarily prevent the default behaviour of ensuing events.
While the current solutions are perfectly correct, they won't work with IE8 and lower, because for those browsers the click
event's which
property always returns 0
no matter which button was used. So I wrote a jQuery plugin, jquery.whichclick to fire extra events: leftclick
, rightclick
, middleclick
and anyclick
— all of which report the correct event.which
and all of which bind stopPropagation
, stopImmediatePropagation
and preventDefault
to the click
event which follows.
Depending on the rest of your code, the plugin would allow you to use:
$( document ).on( 'middleclick', function( e ){
e.preventDefault();
} );
Or:
$( document ).on( 'anyclick', function( e ){
if( e.which === 2 ){
e.preventDefault();
}
else {
// Other conditions you may be looking for...
}
} );
If you don't care about IE support though, this is overkill — just do what the other guys suggested!