I am tryin to implement a custom popup window in Angular. The problem is when clicking outside of the popup when opened i dont know how to implement it easily without an overlay. I have found that in libraries based on jQuery is common to use the .closest
function for this but i can not find an alternative in plain Javascript way.

- 4,095
- 2
- 34
- 44
-
This might be helpful: http://stackoverflow.com/questions/18663941/finding-closest-element-without-jquery – ashfaq.p Nov 11 '14 at 10:26
-
`event.target` can be used? – Jai Nov 11 '14 at 10:30
-
but it uses it by tagname – VuesomeDev Nov 11 '14 at 10:30
-
is ```event.target``` cross browser? – VuesomeDev Nov 11 '14 at 11:49
-
Any workaround on this Blacksonic? – Dhanu Gurung Mar 26 '15 at 11:43
1 Answers
You don't really need closest
method for your task. To be able to close popup on clicking anywhere outside of it, you should bind a click event handler on body
(or document
) element and just close popup if this event is detected there.
It will work due to the fact, that click event bubbles up the DOM tree, eventually reaching topmost element like body
for example.
Then you make sure you prevent event propagation when event is initialized within popup itself, because you don't click event to reach the body (where if handled there popup will be closed). For this you bind one more click event on popup
container and when it occurs you prevent its further propagation:
e.stopPropagation();
So when you interact with popup and its contents clicking inside, doing something, click events never reach the body, so pop up never close. But once you click outside of the popup - bubbling click event will be handled by body
handler and will close popup.

- 191,768
- 25
- 236
- 258
-
The problem with this is that any other element can stop event propagation and it would break it. – VuesomeDev Nov 11 '14 at 11:48