htmx icon indicating copy to clipboard operation
htmx copied to clipboard

hx-wx oob replacements removes focus from input elements

Open eproxus opened this issue 3 years ago • 6 comments

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)

eproxus avatar Jun 08 '21 12:06 eproxus

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 avatar Jun 18 '21 21:06 paxperscientiam

@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 avatar Jun 21 '21 08:06 eproxus

@eproxus Wouldn't it suffice to add an autofocus attribute to your <input> element in the response?

nerdoc avatar Sep 04 '21 13:09 nerdoc

@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 👍

eproxus avatar Sep 15 '21 07:09 eproxus

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,

nerdoc avatar Sep 16 '21 21:09 nerdoc

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).

eproxus avatar Sep 17 '21 05:09 eproxus