Why does adding setTimeout inside the blur event handler eliminate the “masking” of another click handler?

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 .

+7
javascript jquery
source share
3 answers

This is because the blur event occurs before click . The alert() method stops the execution of the script and stops once, the click event does not fire after you release the warning window. Using the setTimeout() method of the blur handler, you actually enable the click event.

I suggest you listen to mousedown instead of a click. The mousedown and blur events occur one after the other when you click the mouse button, but the click only appears when you release it.

+2
source share

This is due to the modal nature of alert() . Try using console.log() instead, and you will see that both of them will be called.

0
source share

setTimeout will fire an event after you have determined .. so you will have more time to click on the text.

on the other hand, the first input does not have time to ignite the blur, so it would be difficult to trigger a click event, but if you click fast enough, you will see two warnings even for the first input.

-one
source share

All Articles