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.
JavaScript code to show the working of this function:
Code: Focuses on an input field on hovering over that field.
javascript
<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 someone 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:
javascript
<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-