How to use focus event?

I would like trigger an action when a text field is active.

It works using click event with the mouse.

But with tab key it is not working.

name() {
  console.log('selected field => name')
}

<div data-action="focus->user#name click->user#name">
  <%= form.label :name %>
  <%= form.text_field :name, autofocus: true %>
</div>

What is the correct way to use focus in a rails form?

The focus event doesn’t bubble so it can’t be handled on a parent element. You could:

  • Move the focus->user#name action to the text field
  • Switch to handling focusin instead

    The focusin event fires when an element is about to receive focus. The main difference between this event and focus is that focusin bubbles while focus does not.

1 Like

focusin worked just perfect

thank you