Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does adding a setTimeout inside a blur event handler fix the "masking" of another click handler?

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.

like image 681
Mark Bennett Avatar asked Apr 15 '16 19:04

Mark Bennett


People also ask

What does blur event do?

The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.

Is Onblur an event handler attribute?

A blur event occurs when a select, text, or textarea field on a form loses focus. The onBlur event handler executes JavaScript code when a blur event occurs. See the relevant objects for the onBlur syntax.

Which is Onblur event is triggered?

The onblur event gets fired when the user navigates to the input field and as soon as leaves the element i.e. the element goes out of focus for the user. The onblur event is the opposite of the onfocus event in which the event is triggered when the input field gets a focus.


1 Answers

It happens because the blur event occurs before the click. The alert() method stops the execution of the script and once stopped, the click event will not fire after you dismiss the alert box. Using the setTimeout() method at the blur handler, you are actually allowing the click event to be fired.

i sugest you to listen to mousedown instead of click. The mousedown and blur events occur one after another when you press the mouse button, but click only occurs when you release it.

like image 88
Marvin Medeiros Avatar answered Oct 13 '22 12:10

Marvin Medeiros