W3cubDocs

/DOM

HTMLElement.focus

The HTMLElement.focus() method sets focus on the specified element, if it can be focused.

Syntax

element.focus()

Examples

Focus on a text field

JavaScript

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

HTML

<input type="text" id="myTextField" value="Text field.">
<p></p>
<button type="button" onclick="focusMethod()">Click me to focus on the text field!</button>

Result

Focus on a button

JavaScript

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

HTML

<button type="button" id="myButton">Click Me!</button>
<p></p>
<button type="button" onclick="focusMethod()">Click me to focus on the button!</button>

Result

Specification

Notes

If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus