LiveView: detect a click outside of an element

I display a dropdown menu if the user clicks on some icon.

Any pointers on how to close that dropdown when the user clicks outside of it?

I would suggest not using liveview for interactions like opening/closing dropdowns in the first place. liveview is great for interactions, which need to contact the server anyways, but for pure client side interactions it’s better to keep things fast and without latency. The simplest way to do this is currently alpine.js, which can be easily integrated with liveview to not lose its state when liveview issues updates to the markup. Alpine also has examples of doing exactly those “click elsewhere” events you need for dropdowns and similar components.

1 Like