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:
- Javascript | Window Blur() and Window Focus() Method
- jQuery | focus() with Examples
- Map in JavaScript
- Map.has( ) In JavaScript
- this in JavaScript
- Map.get( ) In JavaScript
- Functions in JavaScript
- if-else Statement in JavaScript
- JavaScript Quiz | Set-3
- JavaScript | Boolean
- JavaScript | Const
- JavaScript Quiz | Set-2
- JavaScript | Callbacks
- Loops in JavaScript
- JavaScript | weakMap.get()
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.



