Search code examples
javascriptpreventdefault

JS: How to prevent default handling of middle click?


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.


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