Autofocus an input after loading via stream

Hi there! Using Hotwire for a side project and loving it.

I’m building a comment system at the moment, and I’m loading in reply forms via stimulus. I’m wondering if anyone has a good idea on how to autofocus the text box after it’s loaded via stream. HTML’s autofocus property only works on page load.

If I were loading it via javascript or Rails’ old js.erb it’d be simple to just document.getElementById("abc").focus().

Edit: Realised I could solve it with a stimulus controller.

// autofocus_controller.js
import { Controller } from 'stimulus'

export default class extends Controller {
    connect(){
        this.element.focus()
    }
}

I don’t see any immediate downsides of this, but I was wondering if there was anything more idiomatic out there for handling actions after stream content gets injected, or whether anyone foresees any problems with this.

1 Like

I use Hotwire’s turbo frames to load edit forms and the html autofocus works automatically. No need for a stimulus controller at all.

This is the way!

An important lesson when working with Hotwire is that responsibilities are separated. Frames and streams render html, stimulus enhances it. Focusing a field is an enhancement. As your example shows, if the newly injected html declares a controller it will run the connect callback.

2 Likes