Flash message to disappear after 5 seconds?

Is there a way to have a flash message disappear (fade out) after a few seconds, please? Can’t find anything in docs nor on internets. Feels like this could be easy in LiveView, maybe I’m just missing the obvious. Thank you.

You can achieve that with something like this:

Send a message to self when you use put_flash

Process.send_after(self(), :clear_flash, 5000)

Then, in handle_info:

def handle_info(:clear_flash, socket) do
  {:noreply, clear_flash(socket)}
end
3 Likes

That will remove the flash immediately, right? I use some css to accomplish fading out though it is for a different case than flash messages.

@keyframes fade-out {
  from {
    opacity: 1;
  }

  to {
    opacity: 0;
  }
}

.fade-out {
  animation-name: fade-out;
}

.animated {
  animation-duration: 1s;
  animation-fill-mode: both;
}
3 Likes

It appears to me, that the process that put the flash message is dead after it e.g. creates a record. Maybe the send needs to go to different process?

That’s true. If you program the sending to a pid, then push_redirect from the live component, the live view will be shut down and a new one created in its place, thus the old process won’t exist anymore. Changing to push_patch should work.

Also, forgot to mention that you also need to make sure the socket is connected before sending the message:

if connected?(socket), do: ...

@baldwindavid, it will just be removed from the DOM. You could chain together 2 events: 1st fade-out the element (add a css class), then remove it altogether. Worth mentioning that animations are best kept for Javascript, rather than Liveview. You could have a hook on the flash message that will remove itself in 5 seconds with animation effects and everything.

1 Like

Bingo! I’ve combined both of your solutions, and tweaked it a bit. I kept push_redirect rather than push_patch as I was “returning” to index and with push_patch my index of items was not updated.

My workaround is that I actually put the Process.send_after into my mount function, because that’s where I always get back to – so if there’s any new flash message displayed, it gets cleared after 5s. Not sure it’s super robust solution, but this way I need the clear function in one place only, and it works nicely.

And I applied the css animation to nicely fade out the flash, no need for javascript, nor desirable for this simple animation, I think.

3 Likes