We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
<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"– sets the target for better debugging. -
checked={@toggle}– maintains the value of the toggle.
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
This will toggle the value for the checkbox as needed.
<%= 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 %>
Style notes:
-
white-space: pre– preserves white space. -
font-family: monospace– makes the font monospace so each letter and space has the same width.