HTML | DOM FocusEvent

Last Updated : 12 Jul, 2025

The DOM FocusEvent Object contains the events that are related to focus. It includes events like focus in, focus out and blur. The relatedTarget property returns the element related to the element that triggered a focus or blur event. This value is by default set to null due to security reasons. It is a read-only property.

html
<!DOCTYPE html>
<html lang="en">
<body>
 <p>Textarea with id of "text1"</p>
 <textarea id="text1" onfocus="getRelatedTarget()">
  </textarea>
 <p>Textarea with id of "text2"</p>
 <textarea id="text2"></textarea>
 <script>
  function getRelatedTarget() {
   console.log(this.event.relatedTarget);
  }
 </script>
</body>

</html>

Event Types:

  • onblur: This event fires whenever an element loses its focus.
  • onfocus: This event fires whenever an element gets focus.
  • onfocusin: This event fires whenever an event is about to get focus.
  • onfocusout: This event fires whenever an event is about to lose focus.

Example: This example implements the onfocusin event. 

html
<!DOCTYPE html>
<html lang="en">
<body>
 <textarea id="text1" onfocusin="fireEvent()">
 </textarea>
 <script>
  function fireEvent() {
   console.log("The textarea was focused.");
  }
 </script>
</body>
</html>

Example: This example implements the onfocusout event. 

html
<!DOCTYPE html>
<html lang="en">
<body>
 <textarea id="text1" onfocusout="fireEvent()">
 </textarea>
 <script>
  function fireEvent() {
   console.log("The textarea was unfocused.");
  }
 </script>
</body>
</html>
Comment