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

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  

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 compatibility

Feature Chrome Firefox Edge Internet Explorer Opera Safari (WebKit)
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)
focusOptions 64 No support No support No support 51 No support
Feature Android Webview Chrome for Android Firefox Mobile Edge mobile IE mobile Opera Android Safari iOS
Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)  
focusOptions 64 64 No support No support No support 51 No support

See also

Document Tags and Contributors

 Last updated by: EiraGe,