Element: focus イベント

focus イベントは、要素がフォーカスを受け取ったときに発生します。このイベントと focusin との違いは、 focusin がバブリングするのに対し focus はしないことです。

focus の反対は blur です。

バブリング なし
キャンセル 不可
インターフェイス FocusEvent
イベントハンドラープロパティ onfocus
同期 / 非同期 同期
Composed はい

簡単な例

HTML

<form id="form">
  <input type="text" placeholder="text input">
  <input type="password" placeholder="password">
</form>

JavaScript

const password = document.querySelector('input[type="password"]');

password.addEventListener('focus', (event) => {
  event.target.style.background = 'pink';
});

password.addEventListener('blur', (event) => {
  event.target.style.background = '';
});

結果

イベント委譲

このイベントのイベント委譲を実装する方法は二つあります。 focusin イベントを使用するか、 addEventListener()useCapture 引数に true を設定するかです。

HTML

<form id="form">
  <input type="text" placeholder="text input">
  <input type="password" placeholder="password">
</form>

JavaScript

const form = document.getElementById('form');

form.addEventListener('focus', (event) => {
  event.target.style.background = 'pink';
}, true);

form.addEventListener('blur', (event) => {
  event.target.style.background = '';
}, true);

結果

仕様書

Specification
UI Events
# event-type-focus
HTML Standard
# handler-onfocus

ブラウザーの互換性

BCD tables only load in the browser

関連情報