We are looking for an explanation of the answers here and here .
Simply put, I have two elements. Input with onBlur event and div with onClick event. Without any special processing, when I blur the input by clicking on the div, the onBlur event is fired, but the onClick event is not.
However, if I put setTimeout inside the blur event handler, both event handlers are fired 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(); }) });
Demo version of the script here .
javascript jquery
Mark bennett
source share