onBlur killing onClick but not if setTimeout is used

If you put cursor in the first input, then click the button, you get one message.

If you put the cursor in the second one (with the setTimeout), you get both messages.

Why doesn’t the ‘button was clicked’ message display in the first scenario?

Conversely, what is it about the setTimeout that makes the second one show both alerts?

<html>
<head>
  <script type='text/javascript'>
    function testOne() {
      alert('button was clicked');
    }
    function testTwo() {
      alert ('focus left the input');
    }
  </script>
</head>
<body>
  <input name="input1" onblur="testTwo()" />
  <input name="input2" onblur="setTimeout(function(){testTwo();}, 100)" />
  <button name="button1" onclick="testOne()">Button</button>
</body>
</html>

Answer

What you think is happening, is not really happening.

Try it with console.log (which does not block) rather than alert (which does block) and you’ll see that both event handlers do run. Hooray, one more reason to despise alert debugging.

http://jsfiddle.net/mattball/j4cuG/

Leave a Reply

Your email address will not be published. Required fields are marked *