HTML | DOM FocusEvent

The DOM FocusEvent Object contains the events that are related to focus. It includes events like focus in, focus out and blur. 

Properties:

  • relatedTarget: It 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.

Example: Finding out related event with the relatedTarget property. 

html




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM FocusEvent</title>
</head>
 
<body>
    <h1 style="color: green">
        w3wiki
    </h1>
 
    <b>DOM FocusEvent</b>
     
<p>
        The relatedTarget property will
        return the element that will
        return the secondary target.
    </p>
 
     
     
<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>


Output:

  • Focusing on the second textarea:

 

  • Refocusing the first textarea:

 

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>
 
<head>
    <title>DOM FocusEvent</title>
</head>
 
<body>
    <h1 style="color: green">
        w3wiki
    </h1>
 
    <b>DOM FocusEvent</b>
     
     
<p>
        The onfocusin event fires whenever an
        element is about to receive focus.
    </p>
 
     
    <textarea id="text1" onfocusin="fireEvent()">
    </textarea>
     
    <script>
        function fireEvent() {
            console.log("The textarea was focused.");
        }
    </script>
</body>
 
</html>


Output:

  • Before clicking on the textarea:

 

  • After clicking on the textarea:

 

Example: This example implements the onfocusout event. 

html




<!DOCTYPE html>
<html>
 
<head>
    <title>DOM FocusEvent</title>
</head>
 
<body>
    <h1 style="color: green">
        w3wiki
    </h1>
 
    <b>DOM FocusEvent</b>
     
     
<p>
        The onfocusout event fires whenever an
        element is about to lose focus.
    </p>
 
     
    <textarea id="text1" onfocusout="fireEvent()">
    </textarea>
     
    <script>
        function fireEvent() {
            console.log("The textarea was unfocused.");
        }
    </script>
</body>
 
</html>


Output:

  • Before clicking out of the textarea:

 

  • After clicking out of the textarea:

 

Supported Browsers: The browser supported by FocusEvent Object are listed below:

  • Chrome 26
  • Edge 12
  • Firefox 24
  • Internet Explorer 9
  • Safari 7
  • Opera 15