LiveView.JS utility commands and phx-bindings: suggesting `toggle_attribute()` and `phx-has-value`

I gladly use LiveView.JS utility commands and phx-bindings. Sometimes, however, I can’t quite find what I’m looking for.

Alongside LiveView.JS’s set_attribute() and remove_attribute(), a toggle_attribute() can be useful. To easily toggle disable on an input field, for example. Say you want to disable an input field when another input field was given a value by the user. And you want to enable the input field again, when the user removes the value of that other input field. A solution could be triggering toggle_attribute() with a phx-binding that fires when an input field changes from having a value (e.g. “Example”) to not having a value (e.g. “”). Maybe phx-has-value?

JavaScript is, of course, always an option, but I enjoy the times I can use LiveView.JS.

1 Like

I’d suggest looking into JS.dispatch, which can often give you the middleground between implementing custom behaviour, but still triggered/controlled through Phoenix.LiveView.JS.

1 Like

Thank you for the pointer. I am having a look.

Ended up using dispatch already! :upside_down_face:

would make a lot of sense indeed. Same for toggle_class. It would be useful in many situtations, for example to create a button that shows/hides a sidebar, or a dropdown, or some collapsable content. I bet it will be added in future LV versions.

1 Like