The HTMLElement.focus()
method sets focus on the specified element, if it can be focused.
element.focus()
focusMethod = function getFocus() { document.getElementById("myTextField").focus(); }
<input type="text" id="myTextField" value="Text field."> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the text field!</button>
focusMethod = function getFocus() { document.getElementById("myButton").focus(); }
<button type="button" id="myButton">Click Me!</button> <p></p> <button type="button" onclick="focusMethod()">Click me to focus on the button!</button>
Specification | Status | Comment |
---|---|---|
WHATWG HTML Living Standard The definition of 'focus' in that specification. | Living Standard | |
HTML5.1 The definition of 'focus' in that specification. | Recommendation | |
HTML5 The definition of 'focus' in that specification. | Recommendation | |
Document Object Model (DOM) Level 2 HTML Specification The definition of 'focus' in that specification. | Recommendation | |
Document Object Model (DOM) Level 1 Specification The definition of 'focus' in that specification. | Recommendation |
If you call HTMLElement.focus()
from a mousedown event handler, you must call event.preventDefault()
to keep the focus from leaving the HTMLElement
.
HTMLElement.blur()
to remove the focus from an element.document.activeElement
to know which is the currently focused element.
© 2005–2017 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