-1

I'm looking to trigger a dialog function on keyup as long as no input is focused. I have searched around and I have yet to find a solution.

I have tried document.hasFocus() but that didn't work. The function triggered regardless.

Any ideas?

      @HostListener('window:keydown', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (this.router.url.includes('cart') || this.router.url.includes('rack') || document.hasFocus()) {
      console.log(document.activeElement);
      return;
    }
    const dialogConfig = new MatDialogConfig();
    dialogConfig.disableClose = false;
    dialogConfig.hasBackdrop = true;
    const input = String.fromCharCode(event.keyCode);
    if (this.search === '' && /[a-zA-Z0-9]/.test(input)) {
      this.search = event.key;
      dialogConfig.data = this.search;
      const dialogRef = this.dialogService.openDialog(SearchBarComponent, dialogConfig);
      dialogRef.afterClosed().subscribe(
        data => this.search = ''
      );
    }
  }
Kevin Wilde
  • 81
  • 2
  • 9
  • Check this: https://stackoverflow.com/questions/36430561/how-can-i-check-if-my-element-id-has-focus Let me know if worked for you – Jose Vicente Mar 16 '22 at 17:32
  • Bit unclear, some code would help maybe? In general, you’d do a hostbinding to listen to focus and then check your inclusions and exclusions by looming at the event target. – MikeOne Mar 16 '22 at 17:33
  • I want the dialog to pop up if the client does not click any inputs. Updated code to what I tried – Kevin Wilde Mar 16 '22 at 17:39
  • @JoseVicente That didn't work, as that is checking for one specific input, whereas I want to see if ANY input was focused – Kevin Wilde Mar 16 '22 at 17:41
  • Just check the event target and see if the node type is an input..? – MikeOne Mar 16 '22 at 18:00

1 Answers1

0

I figured it out.

I just need to check if the activeElement is the body.

document.activeElement === document.body
Kevin Wilde
  • 81
  • 2
  • 9