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.

2 Likes

I came here to ask this just now trying to make an indicator transform 180 degrees and not disappear.

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")
});
4 Likes

I have an updated solution that supports more complexity inspired by some code I found in LiveBeats



# app.js
const execJS = (selector, attr) => {
  # this executes rendered JS commands on an element
  document.querySelectorAll(selector).forEach(el => liveSocket.execJS(el, el.getAttribute(attr)))
}

window.addEventListener('phx:collapse', e => {
  const id = `#${e.target.id}`

  if (e.target.getAttribute('data-open') === 'true') {
    execJS(id, 'js-hide')
  } else {
    execJS(id, 'js-show')
  }
})
~H"""
<div
  id="my-accordian"
  data-open="false"
  phx-click={JS.dispatch("phx:collapse", to: "#my-accordian")}
  js-show={show()}
  js-hide={hide()}
>
...
</div>
"""
1 Like