We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
Post 20
Game Site Journal - 10 Useable Keyboard
Published on: 2025-04-21
Tags:
elixir, Blog, Side Project, LiveView, Game Site, Html/CSS, Buttons, Clickable, Keyboard, Delete Button
This is going to be a fun one. I want to be able to remove the need for a keyboard on the add and only use the buttons on the keyboard I made on the website. This will take a few steps and I'll go over all of them here. First we need to add a new atom to the state. assign(socket, guess_string: "") or with pipes |> assign(guess_string: "") #This will store the current state of the word being entered Next we update the render logic <.input type="text" value={@guess_string} label="Guess" disabled name="no-input" /> <.input type="hidden" field={@form[:guess]} value={@guess_string} /> This will make sure that we submit the proper word as we will remove the ability to enter words manually. Setting the value of the top one to @guess_string which is set in the hidden field allows us to be sure that you can't use the field and it still gets sent to the event. Now we need to be able to click each letter and have it run an event <%= for key <- [:q, :w, :e, :r, :t, :y, :u, :i, :o, :p] do %> <div phx-click="add_letter" phx-value-letter={Atom.to_string(key)} class={"cursor-pointer w-8 sm:w-10 p-1 sm:p-2 text-center rounded " <> @keyboard[key]}> <%= Atom.to_string(key) |> String.upcase() %> </div> <% end %> Make sure to do this to each row of letters phx-click="add_letter" is the important part. Now we need to add the "add_letter" event to the functions def handle_event("add_letter", %{"letter" => letter}, socket) do current = socket.assigns.guess_string || "" if String.length(current) < 5 do {:noreply, assign(socket, guess_string: current <> letter)} else {:noreply, socket} end end Also we need to be sure to add both of these to any final logic for an assign |> assign(guess_string: "") |> assign(form: to_form(%{"guess" => ""})) This ensures that we don't have any word left in the field after a submit Last 2 steps are to be sure to add a delete button and the the event that handles it. <div class="mt-2 grid grid-cols-3 gap-1 sm:gap-2"> <div phx-click="delete_letter" class="col-span-1 p-2 text-center rounded bg-red-200 cursor-pointer" > Delete </div> </div> I put this with the div for the keyboard but outside any single row of keys def handle_event("delete_letter", _, socket) do updated = socket.assigns.guess_string |> String.slice(0..-2//-1) {:noreply, assign(socket, guess_string: updated)} end This is the logic to remove the last letter from the current letter in the form.
