Home Posts Post Search Tag Search

Game Site Journal - 08 Toggle Helper
Published on: 2025-04-18 Tags: elixir, Blog, LiveView, Game Site, Html/CSS, Buttons

So for this one I wanted to go over the implementation of a toggle switch. I wanted to add this incase there is someone that wants some help doing the Mathematics for a given problem in my MathGame.

First off I need to add in a toggle and then deal with the event within Phoenix LiveView.

  <form phx-change="toggle">
    <label class="toggle-switch">
      <input
        class="toggle-switch-check"
        type="checkbox"
        name="toggle-switch-check"
        checked={@toggle}
      />
      <span aria-hidden="true" class="toggle-switch-bar">
        <span class="toggle-switch-handle"></span>
      </span>
    </label>
  </form>

As you can see some important information here: phx-change=”toggle” #will call the event “toggle” on any change to the field. name=”toggle-switch-check” #will set the target for better debugging checked={@toggle} #will help to maintain the value of the toggle

Once that was done I need to define a couple events that will help us maintain the different states.

def handle_event(“toggle”, %{“toggle-switch-check” => “on”}, socket) do

{:noreply, assign(socket, toggle: true)}

end

def handle_event(“toggle”, _params, socket) do

{:noreply, assign(socket, toggle: false)}

end

Basically this will toggle the value for the checkbox as needed.

Now that we have the check box and a way to change the values we need to set the html to output the vales or nothing.

  <%= if @toggle do %>
    <div style="white-space: pre; font-family: monospace;">
      ... 
      Put your values for what happens when its toggled true
      ...
    </div>
  <% else %>
    <div style="white-space: pre; font-family: monospace;">
      ... 
      Put your values for what happens when its not toggled true
      ...
    </div>
  <% end %>

In this case Ill go over a few things about the style=

white-space: pre #preserve white space font-family: monospace #make the font monospace (very letter and space same width

That is about it for the toggle and dependent information.