--- title: 'Window: focus イベント' slug: Web/API/Window/focus_event tags: - API - Event - Focus - FocusEvent - Reference - Web - Window - onfocus - イベント translation_of: Web/API/Window/focus_event ---
{{APIRef}}

focus イベントは、要素がフォーカスを取得したときに発生します。

focus の反対は {{domxref("Window/blur_event", "blur")}} です。

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

ライブデモ

この例ではフォーカスを失ったときに文書の外見を変更します。 {{domxref("EventTarget.addEventListener()", "addEventListener()")}} を使用して focus および {{domxref("Window/blur_event", "blur")}} イベントを監視します。

HTML

<p id="log">Click on this document to give it focus.</p>

CSS

.paused {
  background: #ddd;
  color: #555;
}

JavaScript

function pause() {
  document.body.classList.add('paused');
  log.textContent = 'FOCUS LOST!';
}

function play() {
  document.body.classList.remove('paused');
  log.textContent = 'This document has focus. Click outside the document to lose focus.';
}

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

window.addEventListener('blur', pause);
window.addEventListener('focus', play);

結果

{{EmbedLiveSample("Live_example")}}

仕様書

仕様書 状態 備考
{{SpecName("UI Events", "#event-type-focus")}} {{Spec2("UI Events")}} Added info that this event is composed.
{{SpecName("DOM3 Events", "#event-type-focus")}} {{Spec2("DOM3 Events")}} 初回定義

ブラウザーの互換性

{{Compat("api.Window.focus_event")}}

関連情報