The HTMLElement.focus() method sets focus on the specified element, if it can be focused.
element.focus(); element.focus(focusOption); // Object parameter
focusOptions Optional
preventScroll Optional
Boolean value: false, the method will scroll the element into the visible area of the browser windowtrue, the method will NOT scroll the element into the visible area of the browser window.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>
focusScrollMethod = function getFocus() {
document.getElementById("myButton").focus({preventScroll:false});
}
focusNoScrollMethod = function getFocusWithoutScrolling() {
document.getElementById("myButton").focus({preventScroll:true});
}
<button type="button" onclick="focusScrollMethod()">Click me to focus on the button!</button> <button type="button" onclick="focusNoScrollMethod()">Click me to focus on the button without scrolling!</button> <div id="container" style="height: 1000px; width: 1000px;"> <button type="button" id="myButton" style="margin-top: 500px;">Click Me!</button> </div>
| Specification | Status | Comment |
|---|---|---|
| HTML Living Standard The definition of 'focus' in that specification. | Living Standard | |
| HTML 5.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. | Obsolete | |
| Document Object Model (DOM) Level 1 Specification The definition of 'focus' in that specification. | Obsolete |
If you call HTMLElement.focus() from a mousedown event handler, you must call event.preventDefault() to keep the focus from leaving the HTMLElement.
| Desktop | ||||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
| Basic support | ? | Yes | 5 | 9 | ? | ? |
| Mobile | |||||||
|---|---|---|---|---|---|---|---|
| Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
| Basic support | ? | ? | Yes | 5 | ? | ? | ? |
HTMLElement.blur() to remove the focus from an element.document.activeElement to know which is the currently focused element.
© 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