Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

JavaScript Focus() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

The JavaScript focus() method is used to give focus to an 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 browsers. 

Syntax:

HTMLElementObject.focus()

Parameters: It does not accept any parameters. 

Return Value: This method does not return any value.

JavaScript examples to show the working of this function:

Example 1: Focuses on an input field by hovering over that field. 

javascript




<script type="text/javascript">
    function myFunction() {
        document.getElementById("focus").focus();
    }
</script>
  
<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>


Output:

 

The focus field can be removed with the help of the blur() method in javascript. Illustration of blur method on clicking a field.

Example: In this example, we will focus on a text input field by clicking a button and remove the focus by clicking the remove focus button.

javascript




<input type="button" onclick="setFocus()" value="set focus">
<input type="button" onclick="removeFocus()" value="remove focus">
<br>
<br>
<input type="text" id="focus">
<script type="text/javascript">
    function setFocus() {
        document.getElementById("focus").focus();
    }
      
    function removeFocus() {
        document.getElementById("focus").blur();
    }
</script>


Output:

 

We have a complete list of Javascript Functions, to check those please go through Javascript Function Complete reference article.


My Personal Notes arrow_drop_up
Last Updated : 22 Dec, 2022
Like Article
Save Article
Similar Reads
Related Tutorials