The following code demonstrates an Example of onBlur and onFocus Event Handlers in JavaScript.

When an element gets the focus, the onfocus event handler executes. In contrast, when the element has lost the focus, the onblur event handler executes. Both of these event handlers can be used in form validation. For example, we can use onblur to determine whether an input field is left blank or not. Similarly, we can use onfocus to show certain information to user which helps in entering the value in an input field.

The following example shows two input text fields. Also, both of these fields handle blur and focus events. When user clicks on another text field, the previous one fires the blur event. Accordingly, the function f1() executes. Similarly, the function f2() executes when a text field gains the focus.

<html>
  <head>
    <title>JavaScript Events</title>
    <script>
      function f1(x)
      {
          x.style.border='3px red solid';
	  x.style.backgroundColor='white';
      }
      function f2(x)
      {
          x.style.border='1px green solid';
          x.style.backgroundColor='skyblue';
      }
    </script>
    <style>
       div{
         margin: 100px;
         padding: 50px;
         border: 2px black solid;
         text-align: center;
        }
    </style>
  </head>
  <body>
  <div>
    <input type="text" id="t1" onblur="f1(this)" onfocus="f2(this)"/>
    <input type="text" id="t2" onblur="f1(this)" onfocus="f2(this)"/>
  </div>
  </body>
</html>

Output

Demonstrating an Example of onBlur and onFocus Event Handlers in JavaScript
Demonstrating an Example of onBlur and onFocus Event Handlers in JavaScript

Further Reading

Evolution of JavaScript from ES1 to ES2020

Introduction to HTML DOM Methods in JavaScript

JavaScript Practice Exercise

Understanding Document Object Model (DOM) in JavaScript

What is Asynchronous JavaScript?

Understanding JSON Web Tokens

Arrow Functions in JavaScript

Understanding HTTP Requests and Responses

Princites