JavaScript - focus() method

revision:


Category : element

The focus() method gives focus to an element (if it can be focused)..

Syntax :

        element.focus()
    

Parameters: none

Examples:

        document.getElementById("myAnchor").focus();
        document.getElementById("myText").focus();
    

Practical examples

example: give focus to ...
Visit my website

Click the buttons to give or remove focus from the link above.


code:
                    <div>
                        <a id="myAnchor" href="https://www.lwitters.com">Visit my website</a>
                        <p>Click the buttons to give or remove focus from the link above.</p>
                        <input type="button" onclick="getfocus()" value="Get focus">
                        <input type="button" onclick="losefocus()" value="Lose focus"><br>
                    </div>
                    <style>
                        a:focus, a:active { color: red;}
                    </style>
                    <script>
                        function getfocus() {
                            document.getElementById("myAnchor").focus();
                            
                        }
                        function losefocus() {
                            document.getElementById("myAnchor").blur();
                                }
                    </script>
                

example: give focus to . . . .

Click the buttons to give or remove focus from the text field.

code:
                    <div>
                        <input type="text" id="myText" value="A text field">
                        <p>Click the buttons to give or remove focus from the text field.</p>
                        <button type="button" onclick="getFocus1()">Get focus</button>
                        <button type="button" onclick="loseFocus1()">Lose focus</button>
                    </div>
                    <script>
                        function getFocus1() {
                            document.getElementById("myText").focus();
                            
                        }
                        function loseFocus1() {
                        document.getElementById("myText").blur();
                        }
                    </script>