JavaScript | Focus()
JavaScript focus method is used to give focus to a html element. It sets the element as the active element in the current document. It can be applied to one html element at a single time in a current document. The element can either be a button or a text field or a window etc. It is supported by all the browsers.
Syntax:
HTMLElementObject.focus()
Parameters: It does not accept any parameters.
Return Value: This method does not return any value.
Code:
Focuses on an input field on hovering over that field.
<html> <head> <script type="text/javascript"> function myFunction() { document.getElementById("focus").focus(); } </script> </head> <body> <form action="#"> <br> <br> <label> Hover me: </label> <input type="text" onmousemove=myFunction() id="focus"> <!-- onmousemove is an event which occurs when somenone hovers the mouse on that particular element and calls the function of javascript --> <br> <br> <label>Without Focus: </label> <input type="text"> <br> <br> <input type="button" value="submit"> </form> </body> </html> |
Output:

Focus field can be removed with the help of blur() method in javascript.
Syntax:
HTMLElementObject.blur()
Parameters: This method does not accept any parameter.
Illustration of blur method on clicking a field:
Code:
<html> <head> <script type="text/javascript"> function setFocus() { document.getElementById("focus").focus(); } function removeFocus() { document.getElementById("focus").blur(); } </script> </head> <body> <input type="button" onclick="setFocus()" value="set focus"> <input type="button" onclick="removeFocus()" value="remove focus"> <br> <br> <input type="text" id="focus"> </body> </html> |
Output:
After clicking on set focus-

After clicking on remove focus-

Recommended Posts:
- Implement a JavaScript when an element loses focus
- Set the focus to HTML form element using JavaScript
- Javascript | Window Blur() and Window Focus() Method
- jQuery | focus() with Examples
- JQuery | Set focus on a form input text field on page load
- Introduction to JavaScript Course | Learn how to Build a task tracker using JavaScript
- JavaScript Course | Understanding Code Structure in JavaScript
- JavaScript Course | Conditional Operator in JavaScript
- JavaScript Course | Printing Hello World in JavaScript
- JavaScript Course | Logical Operators in JavaScript
- JavaScript Course | Data Types in JavaScript
- JavaScript Course | Loops in JavaScript
- JavaScript Course | Objects in JavaScript
- JavaScript Course | JavaScript Prompt Example
- JavaScript Course | Variables in JavaScript
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



