<Script> stops working after live view navigation

Hello,

I have a very similar problem as described here: Tailwind Javascripts stop working after live redirects between liveviews
Only I don’t use Flowbite.

In my header, I have a toggle button to show/hide menu:

<button id="menu_toggle" class="block md:hidden focus:outline-none">
      <.icon name="hero-bars-4" />
</button>

When clicked, this script is called:

<script>
  document.getElementById('menu_toggle').addEventListener('click', function() {
    var accordionContent = document.getElementById('accordionContent');
    accordionContent.classList.toggle('hidden');
  });
</script>

It’s working while I stay on an initial page or navigate somewhere by clicking on the menu items. They are hrefs, so I believe normal http navigation happens.

But when I click a button on the main screen, which results in push_navigate call, then it stops working on the new page. If I refresh the page, it starts working again.

I feel it’s a similar issue to the one described in the link above, but the solution there did not help.

Any help is very welcome!

I think you would probably be better off using the toggle function built into LiveView

I haven’t touched LiveView for a few months but I believe this would work:

<button
  id="menu_toggle"
  class="block md:hidden focus:outline-none"
  phx-click={JS.toggle(to: "#menu_toggle"), in: "fade-in-scale", out: "fade-out-scale"}
>
  <.icon name="hero-bars-4" />
</button>

https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.JS.html#toggle/1

That just works! Thanks a lot!