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

I’m reopening this thread as Phoenix.LiveView.JS is now a thing :slight_smile:

Is there any built-in feature in LiveView.JS similar to AlpineJS click outside?

1 Like

phx-click-away was added in 0.17 (October 2021) as part of this PR:


Perfect! :pray:

not my thread so I cannot acknowledge the solution :white_check_mark: