Track 02 · Lesson 3 of 17Inside the browser

Track 02 · Inside the browser

Keyboard, input and focus events

Lesson 3 of 17· 7 min

Three families of events that are easy to mix up. Press keys in the box, type in the field and click away, and tab between the two inputs to see the difference.

Keys, edits and focus

Try a different keyboard layout if you have one

Key tester

Click here, then press a key

input versus change

0

input events: one per edit

0

change events: when you leave the field

A form section with listeners on this wrapper

0

times the wrapper’s focus listener ran

0

times the wrapper’s focusin listener ran

Click into the inputs, or Tab between them.

key versus code#

On a French keyboard, the key where an English keyboard has Q types an A. event.code is "KeyQ" for both people; event.key is "q" for one and "a" for the other. So:

  • Use key for text and for shortcuts by meaning: "Escape", "Enter", "ArrowDown", "s" for save.
  • Use code when the physical position matters, like WASD movement in a game.
  • Don't use keyCode: it's deprecated and inconsistent.

input versus change#

input fires on every edit. change waits until the value is committed, which for a text field means when it loses focus. Checkboxes and selects fire change immediately, because picking an option is already a commitment.

focus versus focusin#

focus and blur don't bubble, so a listener on a wrapper never hears its children getting focus. focusin and focusout do bubble, which makes them the right choice on a wrapper. In CSS, :focus-within does the same job without any JavaScript.

Check yourself

Which event fires on every keystroke in a text field?