Skip to content

How to execute click function before the blur function

I’ve got a simple issue but I can’t seem to figure out any solution.

Basically I’ve got an input that toggles a dropdown when focused, and when it’s not focused anymore it should close the dropdown.

However, the problem is that if you click on an item in the dropdown, the blur function is executed before the click function of the item, causing the click function not to run at all since the dropdown closes before the click is registered.

How can I solve this?

<input onFocus="showDropdown()" onBlur="hideDropdown()">
<ul>
  <li onClick="myClickFunc()">item</li>
</ul>

Answer

Replace your click event with (mousedown). Mousedown event is called before blur. This code should works properly:

<input (focus)="showDropdown()" (blur)="myBlurFunc()">
<ul>
  <li *ngFor="let item of dropdown" (mousedown)="myClickFunc()">{{item.label}}</li>
</ul>

It looks like click event has lower priority than blur, so it is predictible behaviour that blur event fires first.