Element: focus イベント

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

focus イベントは、要素がフォーカスを受け取ったときに発生します。このイベントはバブリングしませんが、その後に発生する関連する focusin イベントはバブリングします。

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

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

構文

このイベント名を addEventListener() 等のメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

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

onfocus = (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 password = document.querySelector('input[type="password"]');

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

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

結果

イベント委譲

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

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(
  "focus",
  (event) => {
    event.target.style.background = "pink";
  },
  true,
);

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

結果

仕様書

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

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
focus event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

関連情報