I am finding it difficult to synchronize blur and click events. The scenario is as follows: I have a page in which i have a textbox and a button. Now I have a blur event handler for the textbox, which basically makes an AJAX request and updates some part of the page. Also I have a click handler for the button which does some other job.
Now the problem here is that since I have a blur event handler on the textbox, when I enter something in the text box and directly click the button, it fires both blur and click events (as expected). The problem is synchronizing the two since the click handler should only execute once the blur handler has returned (if there was any blur event).
Sample code is as follows:
$('#textbox').on('blur', function(){
//make an ajax request
});
$('#btn').on('click',function(){
//wait for the blur event to finish(if any)
// then execute the code
})
Try something like this:
var blurring = [];
var expecting = false;
$(document).ready(function () {
$('#textbox').on('blur', function () {
// make an ajax request
console.log("TEXTBOX BLURRED");
blurring.push(1); // Flag a new blur event
$.ajax({
url: "/echo/json/",
complete: function () {
setTimeout(function () { // Simulate AJAX request taking 2 seconds
console.log("AJAX REQUEST COMPLETE");
blurring.pop(); // Flag completed blur event
checkClick();
}, 2000);
}
});
});
$('#btn').on('click', function () {
// wait for the blur event to finish(if any)
// then execute the code
console.log("ACTUALLY CLICKED BUTTON");
expecting = true;
checkClick();
});
});
function checkClick() {
if (expecting && blurring.length < 1) {
console.log("CHECKING: EXPECTING CLICK AND NO MORE BLUR EVENTS");
expecting = false;
clickFunction();
} else {
console.log("CHECKING: EITHER NOT EXPECTING OR BLUR EVENT(S) STILL OCCURRING");
}
}
function clickFunction() {
console.log("EXECUTING CLICK FUNCTION");
// Put your actual click code here
}
What you actually want to happen when the button is clicked, put in clickFunction
.