adrianbarbic

adrianbarbic

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.

Showing Posts 1 to 10

Dabsy

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

Dabsy

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>
"""
overcomeoj

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?

Dabsy

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.

trisolaran

trisolaran

More like forgotten by the LV core team I would say. AFAICS they didn’t provide any feedback apart from “we’re aware of this one, just wait”. A useful feature indeed that should be part of the core JS module IMO.

how does it work though? Superficially, it looks like it first removes the class and then adds it, so shouldn’t it always end up adding it? Aren’t the remove_class and add_class commands executed in order?

JohnnyCurran

JohnnyCurran

Technically, yes, but the psuedo class :not selector in the command:

Only adds the class to the #outer-menu element if it does not have .expanded in its class list

Sebb

Sebb

never used LV.JS, so most likely stupid question: why not just use LV to toggle the class?

JohnnyCurran

JohnnyCurran

If you’re asking why not use the LV server state to render the element with / without a certain class, it’s because there are some UI interactions that don’t require a round-trip to the server which (can) introduce a couple hundred ms delay. Things like user profile menus opening/closing should be instantaneous (from a UX perspective) and don’t require the LV to keep track of its open/closed state

I hope that helps and answers your question

soup

soup

I think it implies a kind of “DOM transaction”, probably the changes are applied to a shadow DOM, while the selectors are run against the document DOM? This lets you batch changes up and do tricks like as listed but might also catch you out if you don’t expect it.

See this fiddle, where clicking remove then add (what it “looks” like the LV.JS is doing) is effectively a no-op, which isn’t observed in LV.

trisolaran

trisolaran

That doesn’t explain why it works. The first operation removes the class if the element has it, the second one adds it if the element doesn’t have it. But after the first operation the element is guaranteed not to have the class, so the second operation should always be triggered, resulting in a no-op as @soup has pointed out.

My guess is that the magic is happening here, but I wasn’t able to figure out how exactly.

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
water
I’m aware of 2 such projects, are there others? git: GitHub - team-alembic/realworld: A fullstack Phoenix LiveView application with back...
New
peck
Hi everyone. My team and I have been working on a fairly modest app based around video streaming and chat, but we’ve landed a customer t...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
leoschweizer
Hi, we run different LLM models across a cluster, with each node loading a configurable subset. Model-specific queues let nodes consume ...
New
csmr
Hi all, I’m new here and would like to hear peoples views on my Elixir/Phoenix based game-engine! :smiley: Mutonex gamedesign was finish...
New

Other Trending Topics Top

mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
webofbits
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself. My main conc...
#ai
New
budgie
I love Elixir. It’s one of 2 programming languages I’ve ever fallen in love with. But I don’t use it anymore. Serverless was the promis...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews