jQuery .focusout / .click conflict

The way I solved this was using the mousedown event instead of click. The mousedown event is always triggered before the focusout event while click is not.

You can try it out in the little demo below. Focus on the field and then click on the button.

const field = document.getElementById('field');
const btn = document.getElementById('btn');

btn.addEventListener('click', () => console.log('Click'));
btn.addEventListener('mousedown', () => console.log('Mouse down'));
field.addEventListener('focusout', () => console.log('Focus out'));
<input id="field">
<button id="btn">Try it</button>

As you can see the output is in the following order:

  1. Mouse down
  2. Focus out
  3. Click

This is the most stable solution without using any workaround hacks like timeouts. It also does not depend on jQuery. The only thing worth noting that mousedown does not wait for the user to release their mouse button, but in terms of user experience that is not really a concern here.

Leave a Comment