htmx
htmx copied to clipboard
hx-wx oob replacements removes focus from input elements
Consider the following HTML:
<div hx-ws="connect:/chatroom">
<div id="chat_room"></div>
<form hx-ws="send">
<input id="chat_message" type="text" name="chat_message">
</form>
</div>
The web socket returns messages with this text content:
<input id="chat_message" type="text" name="chat_message">
<div id="chat_room" hx-swap-oob="beforeend">
<div>
<span class="user">Foo</span>
<span class="message">Bar</span>
</div>
</div>
When text is entered into the input box and enter is pressed, the element is correctly replaced but it looses focus.
HTMX version: 1.4.1 Browser: Safari 14.1.1 (16611.2.7.1.4)
For a temporary solution, you could try adding a JS snippet like this to the fetched content (or whatever targeting code makes sense for you): <script>document.getElementsByTagName("input")[0].focus()</script>
@paxperscientiam I currently settled for the following Hyperscript workaround (combined with not returning a new form in the response):
<div hx-ws="connect:/chatroom">
<div id="chat_room"></div>
<form hx-ws="send" _="on submit put '' into #chat_message.value">
<input id="chat_message" type="text" name="chat_message">
</form>
</div>
@eproxus Wouldn't it suffice to add an autofocus
attribute to your <input>
element in the response?
@nerdoc Thanks, that workaround is also feasible. I need to include the form again in the response (obviously). Allows me to get rid of Hyperscript as a dependency 👍
But that doesn't help, as the cursor is at the beginning of the element again. before it was at the end. So writing is impossible,
Well, in my case it does help since I deliver a new empty input (every post is sending a chat message, so clearing the box is what I want).