jQuery lose focus event


The jQuery allows developers to write readable code than JavaScript. We can decrease the 10’s of lines of JavaScript code into the 3 to 4 lines using jQuery.

Sometimes, we need to use jQuery to perform some operation whenever an element loses focus. We can use jQuery's focusOut() and blur() methods to trigger the loose focus event. Mainly, developers require to use it with the inputs, checkboxes, radio buttons, etc., to give the validation feedback to the users once a user completes the input.

Generally, we use the focusout() and blur() methods with the focus() method, which focuses on the input.

Using the FocusOut() Method

The focusOut() method executes the callback function whenever input loses focus. It is an alternative to the ‘focusout’ event in JavaScript. We can execute the focusOut() method by referencing the input elements.

Syntax

Users can follow the syntax below to use the focusOut() method to perform some action when the element loses focus.

$("selector").focusOut(function () {
   //Perform some action
});

In the above syntax, whenever an element loses focus, it will execute the callback function containing the jQuery code.

Example 1

We created the text input in the example below and added the ‘first’ class. Also, we have styled the input element. In jQuery, we used the focusOut() method to remove the ‘first’ class from the input element whenever input loses the focus. Also, we used the focus() method to add the ‘first’ class into the input element when the user focuses on the input element.

In the output, users can click on the input element to focus, click outside to remove focus from the element and observe the changes in the style.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
   <style>
      .first {
         width: 300px;
         height: 50px;
         font-size: 15px;
         text-align: center;
         margin: 30px auto;
         border: 2px solid green;
         color: blue;
         border-radius: 12px;
      }
   </style>
</head>
<body>
   <h2>Using the <i> jQuery's focusOut() </i> method to trigger loose events </h2>
   <input type = "text" id = "focusOut" value = "Click outside to trigger loose event" class = "first" />
   <script>
      // using the focusOut() method to remove the 'first' class when the focus is out of the input field
      $("#focusOut").focusout(function () {
         $(this).removeClass("first");
      });
      // using the focus() method to add the 'first' class when the focus is on the input field
      $("#focusOut").focus(function () {
         $(this).addClass("first");
      });
   </script>
</body>
</html>

Example 2

In the example below, we created the email validator using the focusOut() method. Here, we created an email input field to take email input from users.

In jQuery, we used the focusOut() method to validate email when users click outside the email input field. We used the regular expression with the test() method to validate an email address. We show the message according to the validity of the email address in green or red color.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's focusOut() </i> method to validate email when input loses the focus </h2>
   <input type = "email" id = "email" value = "Enter your email" />
   <div id = "message"> </div>
   <script>
      // validating email
      $("#email").focusout(function () {
      
         // accessing value using id
         var email = $("#email").val();
         
         //If the email is empty, show an error message; Otherwise, continue with the validation
         if (email != "") {
            var regex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/;
            
            // validate email using test() method and regex
            if (regex.test(email)) {
               $("#message").html("Valid Email");
               $("#message").css("color", "green");
            } else {
               $("#message").html("Invalid Email");
               $("#message").css("color", "red");
            }
         } else {
            $("#message").html("Enter Email");
            $("#message").css("color", "red");
         }
      });
   </script>
</body>
</html>

Using the Blur() Method

The blur() method is similar to the focusOut() method. It also executes the callback function whenever users click outside the input element.

Syntax

Users can follow the syntax below to use the blur() method to execute the function when the element loses focus.

$('#text').blur(function () {
   // js code
}); 

The blur() method takes a callback function as a parameter.

Example 3

We created the text input in the HTML section in the example below. In JQuery, we used the blur() method to show a particular message when the element loses focus. Also, we used the focus() method to show a particular message when an element focuses on the input element.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's blur() </i> method to act when an element loses focus</h3>
   <input type = "text" id = "text" placeholder = "click the input">
   <br> <br>
   <div id = "message"> </div>
   <script>
      $('#text').blur(function () {
         $('#message').html('You have lost the focus.');
      });
      $('#text').focus(function () {
         $('#message').html('You have focus on the input.');
      });
   </script>
</body>
</html>

Example 4

In the example below, we created the password strength validator. We added the ‘input’ event on the password input field. So, whenever users change the input value, it will trigger the callback function.

Here, we show password strength based on some factors. Password is very strong if the password’s length is greater than 8, and contains lowercase characters, uppercase characters, and numbers. If it contains only alphabetical characters, a password is a string, and so on.

Whenever users lose focus, we select the text value of the password strength and show the validation message on the web page.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's blur() </i> method to create a password validator</h3>
   <input type = "password" id = "password" placeholder = "Enter your password...">
   <div id = "strength"> </div>
   <div id = "message"> </div>
   <script>
      $('#password').on('input', function () {
         var password = $(this).val();
         if (password.length >= 8) {
            if (password.match(/[A-Z]/) && password.match(/[a-z]/) && password.match(/[0-9]/)) {
               $('#strength').text('Very Strong');
            } else if (password.match(/[A-Z]/) && password.match(/[a-z]/)) {
               $('#strength').text('Strong');
            } else if (password.match(/[A-Z]/)) {
               $('#strength').text('Moderate');
            } else {
               $('#strength').text('Weak');
            }
         } else {
            $('#strength').text('Weak');
         }
      });
      $('#password').blur(function () {
         var strength = $('#strength').text();
         if (strength === 'Weak') {
            $('#message').html('Your password is weak. Please try again.');
         } else {
            $('#message').html('Your password is strong.');
         }
      });
   </script>
</body>
</html>

We learned to trigger the function whenever the input element loses the focus. We used the focusOut() and blur() method to achieve our goal. The difference between the blur() and focusOut() method is that blur() is DOM-specific method, and focusOut() is jQuery-specific method.

Updated on: 05-May-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements