adrianbarbic
Toggle classes with Phoenix.LiveView.JS
Just playing around with Phoenix.LiveView.JS and wondering if there is a way to toggle classes on and off on an element? There is ‘add_class’ and ‘remove_class’ but ‘toggle’ looks like it is just used for showing and hiding. But maybe there is a way but just can’t see it.
Most Liked
Dabsy
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.
Dabsy
I came here to ask this just now trying to make an indicator transform 180 degrees and not disappear.
https://github.com/phoenixframework/phoenix_live_view/pull/1721
It looks like its not in master yet.
I’m using dispatch for now:
js = JS.dispatch(js, "icon:rotate-180", to: "#accordion")
window.addEventListener("icon:rotate-180", e => {
e.target.classList.toggle("transform-rotate-180")
});
overcomeoj
Is there a reason to not merge the PR? Seems like a really popular request and also something built in to JS/DOM with classList.toggle? Maybe it adds too much complexity? Is the PR bad?
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex









