Home > Article > Web Front-end > How to get and lose focus events in jquery
In jquery, you can use the focus() method to obtain the focus event, the syntax "$(selector).focus()"; you can use the blur() method to lose the focus event, the syntax "$(selector).blur ()".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
If there are some form elements in the front-end website that allow users to fill in the content, we can use the focus event and focus loss event in JQ to give the user some prompts. Today we will talk about how to use focus-getting and focus-losing events under JQuery.
focus() method: When an element is selected by clicking the mouse or positioned by the tab key, the element will gain focus.
Syntax:
$(selector).focus()
Copy
Example: The input input box changes the color of its border when it gets focus
Sample code:
<input type="text" name="" id="mochu"> <script> $('#mochu').focus(function(){ $(this).css('border-color','red'); }); </script>
Copy
When the mouse moves into the input and clicks, the input element will change into the following form
jq focus() event will add a CSS style to the input
<input type="text" name="" id="mochu" style="border-color: red;">
Copy
blur() method: The blur event occurs when the element loses focus
Syntax :
$(selector).blur()
Copy
Example: After input loses focus, the content in the input box pops up
Sample code:
<input type="text" name="" id="mochu"> <script> $('#mochu').blur(function(){ alert($(this).val()); }); </script>
Copy
The running results are as shown in the figure:
The blur() lost focus event in JQuery , we can use it to check whether the content entered by the user in the input input box is legal. For example, the following code will give a prompt if the content entered by the user is less than five characters
Sample code:
<input type="text" name="" id="mochu"> <script> $('#mochu').blur(function(){ if($(this).val().length < 5){ alert('字数太少了,多输入几个吧'); } }); </script>
Related tutorial recommendations: jQuery video tutorial
The above is the detailed content of How to get and lose focus events in jquery. For more information, please follow other related articles on the PHP Chinese website!