I have a live view that adds a p
tag with typing...
when a user updates an text input in form element. I want it to remove typing..
when the user blurs out of the text input.
<section class="phx-hero">
<%= if @typing do %>
<p>typing...</p>
<% end %>
<form phx-change="typing" phx-submit="send-message">
<input type="text" phx-blur="stopped-typing" name="msg" value="<%= @msg %>" placeholder="Send message..."/>
<button type="submit" phx-disable-with="Sending...">Submit</button>
</form>
</section>
The events are handled with:
@impl true
def mount(_params, _session, socket) do
{:ok, assign(socket, typing: false, msg: "")}
end
@impl true
def handle_event("send-message", %{"msg" => msg}, socket) do
{:noreply, assign(socket, msg: msg)}
end
@impl true
def handle_event("typing", %{"msg" => msg}, socket) do
{:noreply, assign(socket, typing: true, msg: msg)}
end
@impl true
def handle_event("stopped-typing", _, socket) do
{:noreply, assign(socket, typing: false)}
end
The problem is that when I initially type in the input box, it loses focus and I have to click back into it to continue typing.
I figured out a fix:
I had to wrap the
<p>typing...</>
in a parent containerI think the DOM patch was updating all children of
section
when it added the "typing..." paragraph.