What is the usage of onfocus event in JavaScript?

The onfocus event is triggered when an HTML element receives focus, typically when a user clicks on an input field or navigates to it using the Tab key. This event is commonly used to provide visual feedback or perform actions when users interact with form elements.

Syntax

// HTML attribute
<input onfocus="myFunction()">

// JavaScript event listener
element.onfocus = function() { /* code */ };
element.addEventListener('focus', function() { /* code */ });

Example: Basic onfocus Implementation

<!DOCTYPE html>
<html>
<body>
   <p>Click on the input field to see the onfocus effect:</p>
   <input type="text" id="myInput" onfocus="changeBackground(this)" placeholder="Click here">
   
   <script>
      function changeBackground(element) {
         element.style.background = "lightblue";
         element.style.border = "2px solid blue";
      }
   </script>
</body>
</html>

Using addEventListener Method

The modern approach is to use addEventListener instead of inline event handlers:

<!DOCTYPE html>
<html>
<body>
   <input type="text" id="emailInput" placeholder="Enter your email">
   <p id="message"></p>
   
   <script>
      const input = document.getElementById('emailInput');
      const message = document.getElementById('message');
      
      input.addEventListener('focus', function() {
         this.style.backgroundColor = 'lightyellow';
         message.textContent = 'Email field is now active';
      });
      
      input.addEventListener('blur', function() {
         this.style.backgroundColor = '';
         message.textContent = '';
      });
   </script>
</body>
</html>

Common Use Cases

  • Form validation: Show helpful hints when users focus on input fields
  • Visual feedback: Change colors, borders, or styles to indicate active elements
  • Auto-selection: Select all text in input fields for easy replacement
  • Dynamic content: Load suggestions or display additional information

Focus vs Blur Events

Event Triggers When Common Use
onfocus Element gains focus Show hints, change styling
onblur Element loses focus Validate input, reset styling

Conclusion

The onfocus event enhances user experience by providing immediate feedback when elements receive focus. Use addEventListener for better code organization and combine with onblur for complete focus management.

Updated on: 2026-03-15T23:18:59+05:30

650 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements