jquery
  1. jquery-blur

JQuery blur()

The blur() method in jQuery is used to trigger a blur event on the selected elements. It is often used to handle user action on elements such as input fields, buttons, and dropdown menus.

Syntax

$(selector).blur(function);

The syntax for using the blur() method in jQuery is straightforward. You can select the element(s) you want to apply the blur event to, and then define the function that you want to execute when the element loses focus.

Use

The blur() method is commonly used to perform an action when a user clicks outside of a specific element. For example, you can use it to perform form validation on an input field when a user moves to the next input field or clicks outside of the input field. The blur() method is also useful for handling dropdown menu selections when a user clicks outside of the dropdown menu.

Example

Here is an example of using the blur() method in jQuery to validate an email input field:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Input Validation Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

    <label for="email-input">Email:</label>
    <input type="text" id="email-input">

    <script>
        // Use $(document).ready() to ensure the DOM is fully loaded before executing the script
        $(document).ready(function() {
            // Attach a function to the 'blur' event of the email-input field
            $('#email-input').on('blur', function() {
                // Get the value of the input field
                var emailValue = $(this).val();

                // Define a regular expression pattern for a simple email validation
                var emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

                // Test if the email value matches the pattern
                if (!emailPattern.test(emailValue)) {
                    // Display an alert if the pattern does not match
                    alert('Invalid email format. Please enter a valid email address.');
                }
            });
        });
    </script>
</body>
</html>
Try Playground

In this example, we have defined a function that is executed when the input field with the id email-input loses focus. The function validates the input field value using a regular expression pattern, and if the pattern does not match, an alert message is displayed.

Summary

The blur() method in jQuery is used to trigger a blur event on selected elements. It is commonly used to handle user action on input fields, buttons, and dropdown menus. With its simple syntax and flexible functionality, the blur() method is a useful tool in jQuery for enhancing user experience and performing quick validations.

Published on: