Javascript event listener not working after clicking live_redirect link

I have a Phoenix live view, that uses a live_redirect to link to another liveview.

I have a jquery event listener that I call in a $(document).ready in my app.js.

When I load the page by itself, or refresh it, the JS listener fires as expected, but when I get to the page from the live_redirect link, my JS listener doesn’t fire. I remember having issues like this with Rails turbolinks, and i’m wondering if this could be related.

My JS looks like this

$(document).ready(function () {
   $("#message_form").keydown(function (event) {

My live_redirect looks like this

<li><%= live_redirect, to: Routes.live_path(@socket, MyAppWeb.UserLive, user) %></li>

That event listener is not run when you live navigate (since the document already loaded) and it’s attached to a specific element. So, when you live navigate away from that page and eventually return, there’s nothing that links together the event listener and the “new” html element. You need to set the event listener on each “page update”. This is best done using the phoenix liveview hooks.

In Turbolinks, you would resolve this by listening on a Turbolinks event instead of the document ready:

document.addEventListener("turbolinks:load", function() {
  // ...

You could try the same with LiveView:

window.addEventListener("phx:page-loading-stop", () => {
  // ...

I’ve only used this to setup NProgress loading bar as showcased in the documentation, as I prefer using the Hooks approach for these kind of things.

1 Like

I missed the part of the docs that mentioned "phx:page-loading-stop". But I actually hadn’t even thought of using a hook here, I’m still new to LiveView. I ended up just using a hook instead and that worked perfectly. Thanks!