3

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.

VuesomeDev
  • 4,095
  • 2
  • 34
  • 44

1 Answers1

1

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.

dfsq
  • 191,768
  • 25
  • 236
  • 258