Account
Categories

JavaScript onfocus Event: Field Focus


Definition

When you create a form and use the onfocus function, it highlights the input box or displays a message.

When the user clicks on or moves into the field.

Developers use it to help users fill out the form correctly and know which field is active.

Now you will clearly understand with the help of the flowchart.

Start
   |
   v
Create Form (Name, Contact, Email, Message)
   |
   v
Add onfocus Function --> [This function runs when the user clicks or focuses on a field]
   |
   v
User moves the cursor to a field
   |
   v
onfocus Function runs
   |
   |-- Is it the Name field? --> Show message or highlight
   |-- Is it a Contact field? --> Show message or highlight
   |-- Is it an Email field? --> Show message or highlight
   |-- Is it a Message field? --> Show message or highlight
   |
All done --> User fills data in the field.
   |
   v
End
  

1. In HTML

Syntax:

<input type="text" onfocus="functionName()">

Example:

<input type="text" onfocus="highlightField()">

2. In JavaScript

Syntax:

document.getElementById("fieldId").onfocus = functionName;

Example:

document.getElementById("name").onfocus = function() {
    alert("You clicked on the Name field!");
};