Element: focusin イベント

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

focusin の反対は focusout であり、これは要素がフォーカスを失ったときに発生します。

focusin イベントはキャンセル不可です。

構文

このイベント名を addEventListener() 等のメソッドで使用してください。

js
addEventListener("focusin", (event) => {});

イベント型

FocusEvent です。 Event を継承しています。

Event UIEvent FocusEvent

イベントプロパティ

親である UIEvent および間接的に Event から継承したプロパティもあります

FocusEvent.relatedTarget

もしあれば、フォーカスを受け取った要素。

ライブデモ

HTML

html
<form id="form">
  <label>
    テキストを入力:
    <input type="text" placeholder="テキストを入力" />
  </label>
  <label>
    パスワード:
    <input type="password" placeholder="password" />
  </label>
</form>

JavaScript

js
const form = document.getElementById("form");

form.addEventListener("focusin", (event) => {
  event.target.style.background = "pink";
});

form.addEventListener("focusout", (event) => {
  event.target.style.background = "";
});

結果

仕様書

Specification
UI Events
# event-type-focusin

メモ: UI Events 仕様書ではフォーカスイベントの順序を記述していますが、現在のブラウザーの実装とは異なります。

ブラウザーの互換性

BCD tables only load in the browser

関連情報