Reloading form through turbo stream and `focus()`-ing an element

I am building a typical chat interface:

  • a div with list of messages
  • a form at the bottom;

When the form is submitted, the new message is stored in db and appended through turbo stream into the list of messages. Also the submitted form is replaced with identical form w/o the message (i.e. with empty input field). The problem is that I can’t seem to find an appropriate turbo event that would allow me to focus() the message body input field.

I am wondering if my approach is too complex and I just should use turbo:submit-end or turbo:before-fetch-response and just clear the value of the input field without rerendering the message form?

Something I’ve done in the past in my Hotwire experimentation, I just include an inline <script> tag to focus the element:

<input id="myInput" />

<!-- Run this on view-load. -->
<script type="text/javascript">
    myInput.focus();
</script>

Hotwire will execute / “activate” the inline script when it renders the view. I’ve tried the [autofocus] attribute; but, that only seems to work on the first load of the page, and not on subsequent re-rendering of the view.

2 Likes

Thank you for your response! It seems to work :slight_smile:

Boo ya!! Glad to help.