HTML - attributes - onf...

revision:


"onfocus" attribute : when element gets focus

The onfocus attribute fires the moment that the element gets focus. The onfocus attribute is part of the event attributes and can be used on any HTML element. Onfocus is most often used with <input>, <select>, and <a>. The onfocus attribute is the opposite of the onblur attribute.

syntax

<element onfocus="script"></element>

value: the script value runs when onfocus attribute is called.

some examples

example

A function is triggered when one of the input fields get focus. The function changes the background-color of the input field.

First name:
Last name:

codes:

                    <p class="spec">First name: <input type="text" id="fname" onfocus="myFocus(this.id)"><br>
                    Last name: <input type="text" id="lname" onfocus="myFocus(this.id)"></p>
                    <script>
                        function myFocus(x) {
                        document.getElementById(x).style.background = "yellow";
                        }
                    </script>
                

example

codes:

                    <textarea style="margin-left:3vw;" placeholder="Enter your message here" onfocus="focusFn()" 
                    rows='8' cols="50"></textarea>
                    <script>
                        function focusFn() {
                        document.querySelector('textarea').style.background = '#ffffff36';
                        }
                    </script>