Search code examples
focusblur

HTML focus and blur when input checkbox label clicked


I have an HTML label and HTML input checkbox and I need a stream of focus and blur events that behaves correctly when I click on the label.

(In real app there is a Bootstrap component that hides the input because of styling - so the interaction is not with the checkbox itself but with label styled as checkbox (checkbox itself is invisible, opacity=0).)

The problem is that when I click the label then the real checkbox loses focus (1) (if it previously had focus) and after that it gains the focus again (2). So it generates couple of events blur and focus. I need to get rid of them. This happens only for clicking on the label.

I do not understand why this happens because label should not be focusable.

Example:

  <label for="checkbox">Click On CheckBox Label</label>
  <input type="checkbox" id="checkbox" />
import { of, map, fromEvent } from 'rxjs';

const element = document.querySelector('#checkbox');

fromEvent(element, 'focus').subscribe((event) => console.log('focus'));
fromEvent(element, 'blur').subscribe((event) => console.log('blur'));

Click on label generates two events:

First Click on label:

  • blur // the label gains focus ?
  • focus // checkbox re-gains focus

Second Click on label:

  • blur // the label gains focus ?
  • focus // checkbox re-gains focus

...

I would like to get a RxJS stream of focus and blur as if clicked on real checkbox.

Here is stackblitz demo.

enter image description here


Solution

  • Your problem is not linked to rxjs but basic JS events. blur is trigered on mousedown.

    Just preventDefault on that event to prevent the label from stealing the focus !

    fromEvent(label, 'mousedown').subscribe((event) => event.preventDefault());
    

    Stackblitz