jQuery form events focus() and blur() events

focus() event

Definition and usage

The focus event occurs when an element gains focus.

When an element is selected by mouse click or positioned by tab key, the element will gain focus.

The focus() method triggers the focus event, or specifies a function to run when the focus event occurs.

blur() event


Definition and usage

The blur event occurs when an element loses focus.

blur() function triggers the blur event, or if the function parameter is set, the function can also specify the code to be executed when the blur event occurs.

Tip: Earlier, the blur event only occurred on form elements. In new browsers, this event can be used on any element.

Let’s look at an example below:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
    请输入:<input type="text">

    <script>
        $('input').focus(function(){
            $('input').css('background',"red");
        })

        $('input').blur(function(){
            $('input').css('background',"green");
        })
    </script>
</body>
</html>

When the text box is clicked, the text box gets focus and the background color changes to red

When clicked outside the text box, The text box loses focus and turns green

Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script> </head> <body> 请输入:<input type="text"> <script> $('input').focus(function(){ $('input').css('background',"red"); }) $('input').blur(function(){ $('input').css('background',"green"); }) </script> </body> </html>
submitReset Code