html tutorial - onfocus Attribute in HTML - html5 - html code - html form



Onfocus attribute in html

Learn html - html tutorial - Onfocus attribute in html - html examples - html programs

  • The onfocus attribute is used to trigger an event when the element gets focus.
  • Onfocus is best often used with <input>, <select>, and <a> tags.
  • The onfocus attribute is a section of the Event Attributes.

Syntax for onfocus attribute in HTML:

<element onfocus="script">

Applies To:

Element Attribute
All HTML elements onfocus

Attribute Values:

Value Description
script The script can run on onfocus

Sample Coding for onfocus Attribute in HTML:

Tryit<!DOCTYPE html>
<html>
    <head>
         <title>Wikitechy onfocus attribute</title>
    </head>
    <body>
           <h2>Welcome to Wikitechy</h2>
           <p>Enter Your Name:</p>
           <input type="text" onfocus="onFocus(this)">
           <script>
           function onFocus(obj)
           {
             obj.style.background = "orange";
           }
           </script>
    </body>
</html>

Code Explanation for onfocus Attribute in HTML:

onfocus Attribute Code Explanation

  1. <input> tag defines an input field where the user can enter input.
  2. The onfocus attribute is used to call onFocus () JavaScript function when the textbox gets focused.
  3. onFocus (obj) is a JavaScript function with parameter obj which is used to change the background color as "orange" for the object.

Output for onfocus Attribute in HTML:

onfocus Attribute Tag Output

  1. The output displays a textbox.
onfocus Attribute Tag Output

  1. If user focus the text box, the background color of the text box will be changed into orange color.

Browser Support for onfocus Attribute in HTML:

Yes Yes Yes Yes Yes

Tips and Notes

  • The onfocus attribute is the opposite of the onblur attribute

Related Searches to onfocus attribute in html