HTMLElement.focus()

HTMLElement.focus() メソッドは、指定された要素にフォーカスを設定できる場合、フォーカスを設定します。 フォーカスされた要素は、既定でキーボードや同様のイベントを受け取る要素です。

構文

focus()
focus(options)

引数

options 省略可

フォーカスプロセスの側面を制御するオプションを提供するオプションのオブジェクト。 このオブジェクトには、次のプロパティが含まれる場合があります。

preventScroll 省略可

論理値で、ブラウザーが文書をスクロールして、新しくフォーカスされた要素を表示するかどうかを示します。 preventScroll の値が false(既定値)の場合、ブラウザーは要素をフォーカスした後、その要素をスクロールして表示します。 preventScrolltrue に設定されている場合、スクロールしません。

テキストフィールドにフォーカスする

JavaScript

focusMethod = function getFocus() {
  document.getElementById("myTextField").focus();
}

HTML

<input type="text" id="myTextField" value="テキストフィールド">
<p></p>
<button type="button" onclick="focusMethod()">クリックしてテキストフィールドにフォーカスしてください。</button>

結果

ボタンにフォーカスする

JavaScript

focusMethod = function getFocus() {
  document.getElementById("myButton").focus();
}

HTML

<button type="button" id="myButton">クリックしてください</button>
<p></p>
<button type="button" onclick="focusMethod()">クリックするとボタンにフォーカスします。</button>

結果

focusOption でフォーカスする

JavaScript

focusScrollMethod = function getFocus() {
  document.getElementById("myButton").focus({preventScroll:false});
}
focusNoScrollMethod = function getFocusWithoutScrolling() {
  document.getElementById("myButton").focus({preventScroll:true});
}

HTML

<button type="button" onclick="focusScrollMethod()">クリックするとボタンにフォーカスします。</button>
<button type="button" onclick="focusNoScrollMethod()">クリックするとスクロールせずにボタンにフォーカスします。</button>

<div id="container" style="height: 1000px; width: 1000px;">
<button type="button" id="myButton" style="margin-top: 500px;">クリックしてください</button>
</div>

結果

仕様書

Specification
HTML Standard
# dom-focus-dev

メモ

  • HTMLElement.focus() をmousedown イベントハンドラーから呼び出した場合、 HTMLElement からフォーカスが外れないように event.preventDefault() を呼び出す必要があります。
  • tabindexシャドウ DOM など、これまで仕様が定まらないままだった様々な HTML 機能に関するフォーカスの挙動が、最近(2019 年 10 月に)更新されました。詳しくは WHATWG blog をチェックしてみてください。

ブラウザーの互換性

BCD tables only load in the browser

関連情報

  • HTMLElement.blur で要素からフォーカスを取り除きます。
  • document.activeElement で現在フォーカスされている要素を知ることができます。
  • focusin イベント: 要素がフォーカスを得ようとしているときに発行されます。
  • focusout イベント: 要素がフォーカスを失おうとしているときに発行されます。