W3cubDocs

/DOM

HTMLElement.focus

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

Syntax

element.focus();
element.focus(focusOption); // Object parameter

Parameters

focusOptions Optional
Is an Object with the following property:
preventScroll Optional
Is a Boolean value:
  • If false, the method will scroll the element into the visible area of the browser window
  • If true, the method will NOT scroll the element into the visible area of the browser window.

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

Focus with 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()">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>

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.

Browser compatibilityUpdate compatibility data on GitHub

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 ? ? ?

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