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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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:

filter_none

edit
close

play_arrow

link
brightness_4
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>

chevron_right


Output:
After clicking on set focus-

After clicking on remove focus-



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.