onblur

The onblur event is triggered when an HTML element loses focus. This event is commonly used with input fields.

onblur event

The onblurevent is activated when an element loses focus. It is frequently used with form elements, like <input>. To implement it, assign a <script> that will execute when focus is moved away from the element.

Syntax

In HTML

index.html
<element onblur="myScript">

In JS

script.js
object.onblur = function(){myScript};

In JavaScript, the addEventListener() function is used.

script.js
object.addEventListener("blur", myScript);

Example

::event-onblur ::
index.html
<!DOCTYPE html>
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The blur Event</h2>
Enter your name: <input type="text" id="fname" onblur="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>

<script>
function myFunction() {
  let x = document.getElementById("fname");
  x.value = x.value.toUpperCase();
}
</script>

</body>
</html>

Value

The onblur attribute is the counterpart to the onfocus attribute.

Conclusion

The onblur event is triggered when an element loses focus, commonly used with form elements. It allows developers to execute a function when focus is moved away from an element. This event complements the onfocus event for handling user interactions effectively.