Looking for an explanation to the answers provided here and here.
Put simply, I have two elements. An input with an onBlur event, and a div with an onClick event. Without any special handling, when I blur the input by clicking the div, the onBlur event is fired, while the onClick event is not.
However, if I put a setTimeout inside the blur event handler, both event handlers are called when I click on the div. Why does this work?
HTML:
<input type="text" name="input" id="input1" />
<div id="div1">Focus the input above and then click me. (Will see 1 alert)</div>
<br/>
<input type="text" name="input" id="input2" />
<div id="div2">Focus the input above and then click me. (Will see 2 alerts)</div>
Javascript:
$(document).ready(function() {
function clickHandler() {
alert('Click!');
}
function blurHandler() {
alert('Blur!');
}
$('#input1').on('blur', function() {
blurHandler();
})
$('#input2').on('blur', function() {
window.setTimeout(blurHandler, 200);
})
$('#div1').on('click', function() {
clickHandler();
})
$('#div2').on('click', function() {
clickHandler();
})
});
Fiddle demo is here.