Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 407
David Rettenbacher Avatar asked Sep 24 '13 08:09

David Rettenbacher


People also ask

How to prevent Default action in JavaScript?

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

What does event preventDefault() do?

Event.preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.

What is preventDefault in angular?

preventDefault() prevents the default behaviour, it is not related to bubbling or not the events, so you can safely ignore it.


1 Answers

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

like image 107
Moritz Roessler Avatar answered Oct 14 '22 10:10

Moritz Roessler