jQuery Event blur() Method



The jQuery event blur() method is used to either trigger the blur event on the selected elements or to bind (or attach) a function that will run when the blur event occurs. This method is generally used with <input> and <textarea> fields to blur focus when users click outside of them.

Syntax

Following is the syntax of the jQuery event blur() method −

$(selector).blur(function)

Parameters

This method accepts an optional parameter as 'function', which is described below −

  • function (optional) − The function is to run whenever the blur event occurs on the selected elements.

Return Value

This method does not return any value but triggers the blur event on the selected element.

Example 1

The following program demonstrates the usage of the jQuery event blur() method −

<html>
    <head>
        <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <input type="text" placeholder="Your name">
    <p>Enter something in input field and click outside the input field to lose the focus.</p>
    <script>
        $('input').blur(function(){
            alert("Input contents: " + $(this).val());
        });
    </script>
</body>
</html>

Output

After the program is executed, it will display an input field. When the user types something into this field and then clicks outside of it, the field will lose focus (triggering the blur event) −


After clicking on the "ok" button, you will able to see that the input field lost its focus −


Example 2

The following is another example of the jQuery event blur() method. Here, we use this method to bind a function that will run (execute) when the blur event occurs (trigger) on the selected elements −

<html>
    <head>
        <script type = "text/javascript" src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
      </script>
    </head>
<body>
    <p>Enter something in textarea field and click outside the field to lose the focus.</p>
    <p>Write your feedback</p>
    <textarea name="" id="" cols="30" rows="10" placeholder="feedback...."></textarea>
    <span></span>
    <script>
        $('textarea').blur(function add(){
            document.querySelector('span').innerHTML = $(this).val();
        });
    </script>
</body>
</html>

Output

After executing the above program, a textarea field will be displayed. When the user enters text and then clicks outside the field, the blur event will be triggered, and the field lose focus −


jquery_ref_events.htm
Advertisements