The lose focus event in jQuery, occurs when an input field is no longer active, such as when a user clicks outside of it. This event is useful for validating input or triggering actions when the user navigates away from a field.
Below are the two ways for JQuery lose focus events:
1. Trigerring lose focus event using Focusout()
Focusout() in JavaScript triggers when an element loses focus, such as when a user clicks outside of an input field. It works on both the element losing focus and its child elements. It's commonly used to detect when a user has moved away from an element and can be applied to improve user interactions or validate form fields.
<!DOCTYPE html>
<html>
<head>
<title>Using Focusout for lose focus event</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<div style="border: 1px dashed green;padding:10px;">
Course: <input type="text"><br>
</div>
<p>
Clicking outside the input text field enables
triggering of focusout event.
</p>
<script>
$(document).ready(function () {
$("div").focusin(function () {
$(this).css("background-color", "#008000");
});
$("div").focusout(function () {
$(this).css("background-color", "#FFFFFF");
});
});
</script>
</body>
</html>
2. Trigerring lose focus event using Blur()
Blur() in JavaScript triggers when an element loses focus, like when a user clicks away from an input or textarea. Unlike focusout(), it only applies to the element itself, not its child elements, making it ideal for handling simple focus-loss events on individual elements.
<!DOCTYPE html>
<html>
<head>
<title>Using blur for lose focus event</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
</head>
<body>
<div style="border: 1px dashed green;padding:10px;">
Course: <input type="text"><br>
</div>
<p>
Clicking outside the input text field
enables triggering of blur event.
</p>
<script>
$(document).ready(function () {
$("input").blur(function () {
alert("Losefocus event occurs");
});
});
</script>
</body>
</html>