1

The following code cancels left clicks and middle clicks on the whole page:

<script> $(document).on('click',false) </script>
<a href="http://example.com">link</a>

This other code uses a jquery delegated event to cancel clicks on A elements only:

<script> $(document).on('click','a',false) </script>
<a href="http://example.com">link</a>

which works fine for left clicks, but if you middle click the link, a new tab is opened, which means the event was not cancelled.

Why using the second code, middle clicks are not cancellled?

GetFree
  • 40,278
  • 18
  • 77
  • 104
  • 2
    `click` is the left button, by definition. you can use `mousedown` – dandavis Dec 30 '15 at 21:28
  • @dandavis, first time I hear that. Where is that documented? – GetFree Dec 30 '15 at 21:32
  • 1
    Detecting middle click: http://stackoverflow.com/a/5393604/816620 and http://stackoverflow.com/questions/17130852/detecting-middle-mouse-click-event-jquery – jfriend00 Dec 30 '15 at 21:33
  • i don't know where it's documented, but that's always been the way it is... – dandavis Dec 30 '15 at 21:35
  • @dandavis, then why the first code can cancel middle clicks just fine? – GetFree Dec 30 '15 at 21:38
  • i suspect that click is synthetic on A tags. for example, pressing [Enter] on a – dandavis Dec 30 '15 at 21:45
  • @dandavis, I included the first code to show that it's not too late to cancel an event when it bubbled all the way up to the document. – GetFree Dec 30 '15 at 21:52
  • if my understanding of jq events is correct, the first one is not delegated, the click still "happens" on the A tag (during capturing phase). the delegated one uses a mother function (coded by jq) on document that examines the event args and executes jq-subscribed events that match criteria, so the event really "happens" on document, even if jq makes it appear otherwise. – dandavis Dec 30 '15 at 21:56

1 Answers1

0

jQuery explicitly disallow non-left-clicks on delegated events, as can be seen on the source code, line 357: https://github.com/jquery/jquery/blob/1de834672959636da8c06263c3530226b17a84c3/src/event.js#L357

The reason:
Firefox doesn't support middle-click events, so they decided to disallow the feature for all browsers.

As a workarond, the expression

$(document).on('click','a',false)

can be converted to the functionaly equivalent

$(document).click(function(evt){ if($(evt.target).closest('a').length) return false })
GetFree
  • 40,278
  • 18
  • 77
  • 104