Toggle classes with Phoenix.LiveView.JS

Not sure, I just again came in search of this functionality again two days back so I checked the PR to see why it hadn’t gone forward – just appears abandoned.

The updated solution from begleynk worked like a charm for me though.

Crossposting suggested solution for future searchers:

def toggle_expanded(js \\ %JS{}) do
  js
  |> JS.remove_class(
    "expanded",
    to: "#outer-menu.expanded"
  )
  |> JS.add_class(
    "expanded",
    to: "#outer-menu:not(.expanded)"
  )
end

It adds the class if it does not exist on the element and removes it if it does.