How do I handle a click anywhere in the page, even when a certain element stops the propagation?

Sander picture Sander · Nov 8, 2011 · Viewed 103.3k times · Source

We are working on a JavaScript tool that has older code in it, so we cannot re-write the whole tool.

Now, a menu was added position fixed to the bottom and the client would very much like it to have a toggle button to open and close the menu, except closing needs to happen automatically when a user starts doing things out side of the menu, for example, when a user goes back into the page, and selects something or clicks on a form field.

This could technically work with a click event on the body, triggering on any click, however there are numerous items in the older code, where a click event was handled on an internal link, and return false was added to the click function, in order for the site not to continue to the link's href tag.

So clearly, a general function like this does work, but not when clicked on an internal link where the return false stops the propagation.

$('body').click(function(){
  console.log('clicked');
});

Is there a way I can force the body click event anyway, or is there another way I can let the menu dissappear, using some global click event or anything similar?

Without having to rewrite all other clicks in the application that were created years ago. That would be a monster task, especially since I have no clue how I would rewrite them, without the return false, but still don't let them go to their href.

Answer

Andy E picture Andy E · Nov 8, 2011

Events in modern DOM implementations have two phases, capturing and bubbling. The capturing phase is the first phase, flowing from the defaultView of the document to the event target, followed by the bubbling phase, flowing from the event target back to the defaultView. For more information, see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow.

To handle the capturing phase of an event, you need to set the third argument for addEventListener to true:

document.body.addEventListener('click', fn, true); 

Sadly, as Wesley mentioned, the capturing phase of an event cannot be handled reliably, or at all, in older browsers.

One possible solution is to handle the mouseup event instead, since event order for clicks is:

  1. mousedown
  2. mouseup
  3. click

If you can be sure you have no handlers cancelling the mouseup event, then this is one way (and, arguably, a better way) to go. Another thing to note is that many, if not most (if not all), UI menus disappear on mouse down.