Blog Post: My Favorite new LiveView Feature: JS.toggle_class/1

Phoenix LiveView v0.20.4 offers a hidden gem with its handy little JS.toggle_class/1 feature. This addition simplifies toggling classes for developers, allowing for effortless visibility changes, multi-element toggles, and even animated transitions—all without needing additional tools. Check out the examples showcasing basic visibility toggles, simultaneous class manipulations, dynamic list item interactions, reusable click events, and more! Could this become your new favorite LiveView feature?

13 Likes

Great tutorial!

There needs to be more Live View JS tutorials.

Wish I read this a month ago when I was building out modals and working through live view JS.

4 Likes

I agree. The JS features are powerfully but still hard to get your heads around.

1 Like

@brainlid Thanks for highlighting this new function with so many examples :slight_smile:

Two ingenious use cases:

  • replace classes by mentioning them both in the initial state and the toggle:
<.icon
  name="hero-bars-3"
  class="lg:hidden cursor-pointer"
  phx-click={JS.toggle_class("hero-bars-3 hero-x-mark")}
/>
  • simultaneously hide one element and show another (also some form of “replace”) by having multiple targets with different initial state. This one borrowed from the blog post:
<div
  id="example-2"
  phx-click={
    JS.toggle_class("hidden",
      to: ["#example-2 > .title-content", "#example-2 > .expanded-content"]
    )
  }
  class="px-4 py-3 cursor-pointer bg-purple-100 rounded-md border border-purple-300 text-purple-600"
>
  <div class="title-content font-medium">Click to reveal the text</div>
  <div class="expanded-content hidden mt-2 text-purple-800 text-md font-light">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  </div>
</div>
5 Likes

Glad this was added, making toggle menus and content was not much fun before :smiley:

1 Like

Agreed! Such a handy feature.

I like the hero graphic swap example too! Nice!