This is a short snippet on how to do fade-out on @flash outputs, for Phoenix LiveView 0.17! Yes the latest one, utilizing Phoenix.LiveView.JS commands.
The effect I was going for was when there are new flashes, the flash would automatically fade out, after waiting a couple seconds, so that the user will be nudged but message will still fade away.
This will do the animation, and then lastly fire a JS.push()
to clear out the flash at the server.
Files that are needed are:
app.js
- to set up event handler to processing event message coming from server, and to run the JS command assigned to target attributecomponent.ex
- your LiveComponent filecomponent.html.heex
- code for showing flash, and to have the target attribute, andphx-value-key
attributetailwind.config.js
- optional, just showing how to add custom duration / delays if you need them
Check out the code in its entirety here:
Oh, and this uses TailwindCSS. If you don’t use TailwindCSS, you can look at https://tailwindcss.com/docs to get the one-to-one translation from Tailwind to CSS styling.
References:
- Idea for sending event into DOM(ElixirForum)
- Phoenix.LiveView.JS.hide()
- Phoenix.LiveView.JS.push()
- Chris McCord’s KeyNote for JS Commands Feature(Youtube)
This is so cool. Not gonna lie. Updating pre-0.15 Phoenix LiveView into 0.17.5 just to do this took me two days, and was just about to give up yesterday.
Before this I relied on a hack to just fade out, but the flash would still be there. It was hard to time the various things going on during an animated fading-out of flashes, because it involved both server and DOM to act in unison:
- Fade things out, and LiveView shouldn’t trigger a rerender during that time
- AFTER animation is done, remove that flash
What I was doing was very hacky. And if I did want to do it right, I’d have to have a whole pipeline of hook + alpineJS to get it up and running, which seems too much lift for small amount of feature footprint.
But now, it’s so much more streamlined, with very small footprint being created. I love it.