SoFunction
Updated on 2025-02-28

jQuery solves conflicts between blur event of input element and click event of other non-form elements

HTML structure: It's very simple, just one input or one div, it's OK to explain the problem;

<input type="text" value="default value"><br/><br/><div>search</div>

The result you want to achieve:

1. The value is "" when the input box obtains the focus, and the value is "default value" when the focus is lost; ------This is easy to implement;

2. After entering the content to be searched in the input box, click the div search and ask the console to print out the content to be searched (of course, the requirements of each project are different, here is just an example), and it is required that the focus and blur behavior of the input will not be affected after clicking; ----This is the key point

Let’s first look at the effect of the conflict before it has not been resolved;

$("input").focus(function () { 
 = ""; }).blur(function () { 
 = "default value"; });$("div").click(function () { 
var value = $("input").val(); 
(value); });

Result: Enter "aaaa" in the input and click on the div, but the console outputs "default value", which does not match the expected result;

Solution 1:Add a timer to the callback function of the blur to delay the execution time of the blur callback function. In this way, although the input's blur behavior is triggered first when clicking the div, due to the timer delay, you have to wait until the div click callback execution is completed before the input's blur behavior can be executed;

$("input").focus(function () { 
 = "";}).blur(function () { 
var self=this; 
setTimeout(function(){ 
 = "default value"; 
},300)}); $("div").click(function () {//This part remains unchangedvar value = $("input").val(); 
(value); });

Result: Enter "aaaa" in the input and click on the div, but the console outputs "aaaa" which meets the expected result;

Solution 2:Change the click event of the div to the mousedown event, because the mousedown behavior is triggered when the mouse is clicked, and the click behavior is triggered when the mouse is clicked and lifted.

$("input").focus(function () {//This part remains unchanged = "";}).blur(function () { 
 = "default value";}); $("div").mousedown(function () { 
var value = $("input").val(); 
(value); });

Result: Enter "aaaa" in the input and click on the div, but the console outputs "aaaa" which meets the expected result;

The above is the editor’s introduction to jQuery to solve the conflict between the Blur event of the input element and other non-form elements of the click event. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!