Dynamically adding html to a LiveView page

I used js to add some html to a page, e.g. on a button click display a message in a div, but when the state on the page changes, LiveView re-renders the html, as described in the docs:

Any time a stateful view changes or updates its socket assigns, it is automatically re-rendered and the updates are pushed to the client.

The result is my message div is lost. And, if I use js to add a div with a message in response to a state change, then the message just flashes for a millisecond before the whole page updates.

How do you handle something like that?

Check out LiveView’s built-in JS Client Utility Commands, especially JS.show and JS.hide.


Provides commands for executing JavaScript utility operations on the client.

JS commands support a variety of utility operations for common client-side needs, such as adding or removing CSS classes, setting or removing tag attributes, showing or hiding content, and transitioning in and out with animations. While these operations can be accomplished via client-side hooks, JS commands are DOM-patch aware, so operations applied by the JS APIs will stick to elements across patches from the server.
In addition to purely client-side utilities, the JS commands include a rich push API, for extending the default phx- binding pushes with options to customize targets, loading states, and additional payload values.

Client Utility Commands

The following utilities are included:

  • add_class - Add classes to elements, with optional transitions
  • remove_class - Remove classes from elements, with optional transitions
  • set_attribute - Set an attribute on elements
  • remove_attribute - Remove an attribute from elements
  • show - Show elements, with optional transitions
  • hide - Hide elements, with optional transitions
  • toggle - Shows or hides elements based on visibility, with optional transitions
  • transition - Apply a temporary transition to elements for animations
  • dispatch - Dispatch a DOM event to elements
1 Like