Question

It seems like a ridiculous easy problem but it appears to be harder...

I want to prevent the default handling of an middle click. I created a JSFiddle and threw in stopPropagation, stopImmediatePropagation, preventDefault and return false - like this:

$(document).on("mousedown", "a", function(e)
{    
    console.log("\nprevent mousedown...");
    e.stopPropagation();
    e.stopImmediatePropagation();
    e.preventDefault();
    console.log("...mousedown prevented");
    return false;
});

But the middle-click is fired. BTW it is fired by the time I release the middle button. Here's the JSFiddle: http://jsfiddle.net/Gq4p9/4/

Tested on Chrome 29, Firefox 23 and IE11.

I hope someone of you can find out, why this script doesn't prevent the default handling.

Was it helpful?

Solution

As you mentioned in the comments, it works if you pass a jQuery object as selector

$(document).on ("click", $("a"), function (e) { ...

though the API says selector is expected to be of type string.

Fiddle


Also you could always just use a plain javascript click eventListener.

link.addEventListener ("click", function (e) {
  if (e.which === 2) 
      e.preventDefault();
})

Heres a Fiddle

OTHER TIPS

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!

what you are looking for is this condition:

    if( e.which == 2 ) { 
        // prevent default behaviour
    }

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top