Search code examples
javascriptprototypejs

Prototype best practice for "click anywhere to close"?


I find myself very often in the situation that I open an element in a web page - e.g. a drop-down menu - that I want to close if the user clicks anywhere on the page except the element itself.

To keep things simple, I have mostly written the code myself instead of employing some drop-down menu class.

However, I have never managed to build an implementation of this that was completely satisfying: Event handling and bubbling would work differently in different browsers, there would be the need for nasty workarounds, in some situations clicking the drop-down button would start closing it in the same moment, and so on.

Is there a Prototype based, authoritative, best practice to do this? Something that works across browsers - IE6 being a plus but not a requirement?

Just this:

  • click on a button - an element opens (e.g. an absolutely positioned drop-down menu).
  • click within the element - the element stays open.
  • click on the button that opened the element - the element stays open.
  • click anywhere else on the page - the element closes.

I need help with the event handling part only, the displaying of the menu is totally secondary.


Solution

  • Event.observe(document, 'click', function (event) {
      switch (event.element().id) {
        case 'example_id':
          // do different stuff depending on element clicked
          // ofc u don't need to pass id, u can simply throw an element itself
          break;
        default:
          // do close action
          break;
      }
      // also check Event.findElement();
    });
    

    You can also add specific classes to the items you don't want to trigger close action and check it inside

    if (!event.element().hasClassName('dont_close'))   
      Element.remove(selectDOMElement);