Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focusout and blur not working in Angular

Tags:

angular

I am trying to detect when the user clicks off the div. I added this code in component.html

  <div class="h unselected" contenteditable="false" (mousedown)="mousedown($event)" (mouseup)="mouseup($event)" (focusout)="focusout($event)" (blur)="focusout($event)">
    Hello
  </div>

component.ts has focusout(e) implemented (among other things)

focusout(e){
    console.log("f out");
  }

The method never gets fired when I click outside of the Hello div. Why is that? I am using Chrome.

like image 979
sanjihan Avatar asked Dec 12 '25 14:12

sanjihan


2 Answers

Set tabindex on the div. The tabindex indicates if its element can be focused.

<div tabindex="-1" class="h unselected" contenteditable="false" (mousedown)="mousedown($event)" (mouseup)="mouseup($event)" (focusout)="focusout($event)" (blur)="focusout($event)">
    Hello
  </div>

Why -1?

According to the mozilla web docs:

A negative value (usually tabindex="-1") means that the element should be focusable, but should not be reachable via sequential keyboard navigation. Mostly useful to create accessible widgets with JavaScript.

tabindex="0" means that the element should be focusable in sequential keyboard navigation, but its order is defined by the document's source order.

A positive value means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. That is, tabindex="4" would be focused before tabindex="5", but after tabindex="3". If multiple elements share the same positive tabindex value, their order relative to each other follows their position in the document source.

like image 112
oreofeolurin Avatar answered Dec 14 '25 06:12

oreofeolurin


Not all elements support focusing by default. div is one of them.

Any element can support focusing if it has tabIndex attribute.

So i would try:

<div tabindex="-1" ...></div

Plunker Example

See more details about tabindex https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex

like image 25
yurzui Avatar answered Dec 14 '25 05:12

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!