Search code examples
javascriptprototypejs

Hiding Layers on click observer


I have many layers in the Documents that will be displayed on different user interactions. Now I want to hide these Layer if user clicks anywhere else in the Document. These layer have different IDs.

Is there any generic way to register only a single Observer for all such layers?


Solution

  • You can just add a click event listener to the document.body node and inspect the event.target property to see if it's inside or outside your layers, this should work fine in the bubbling phase if you don't stopPropagation of the event anywhere, however you can capture it in the capturing phase by supplying true as the last argument to addEventListener if that isn't the case. Making this cross-browser compatible is left as an exercise to the reader.