Open In App

JavaScript Focus() Method

Improve
Improve
Like Article
Like
Save
Share
Report

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

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

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</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>
    <script type="text/javascript">
        function myFunction() {
            document.getElementById("focus").focus();
        }
    </script>
</body>
 
</html>


Output:

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.

HTML




<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
    content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</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">
    <script type="text/javascript">
        function setFocus() {
            document.getElementById("focus").focus();
        }
 
        function removeFocus() {
            document.getElementById("focus").blur();
        }
    </script>
</body>
 
</html>


Output:

Output

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



Last Updated : 08 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads