Basic View Toggle of DOM Element Using JS in Elixir Phoenix LiveView

From ElixirBlocks
Jump to: navigation, search


  def render(assigns) do
    ~H"""
    <div id="item">My Item</div>

    <button phx-click={JS.toggle(to: "#item")}>
      toggle item!
    </button>
    """
  end


Another Example

defmodule AppWeb.SandboxLive do
  use AppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, socket}
  end

  def button_event("invoke_writing") do
    %JS{}
    |> JS.remove_class("active", to: "#writing_button")
    |> JS.add_class("hidden", to: "#writing_button")
    |> JS.remove_class("hidden", to: "#preview_button")
    |> JS.add_class("active", to: "#preview_button")
  end

  def button_event("invoke_preview") do
    %JS{}
    |> JS.remove_class("active", to: "#preview_button")
    |> JS.add_class("hidden", to: "#preview_button")
    |> JS.remove_class("hidden", to: "#writing_button")
    |> JS.add_class("active", to: "#writing_button")
  end

  def render(assigns) do
    ~H"""
    <button phx-click={button_event("invoke_writing")} id="writing_button" class="hidden">
      Preview
    </button>
    <button phx-click={button_event("invoke_preview")} id="preview_button">
      Writing
    </button>
    """
  end
end