Checking for focus and hover with JavaScript

Viewed 17

I want to find out wether my HTML Event is on focus (not if it is clicked but focused by navigating with the keyboard).

myElement === document.activeElement

is only true when the element is clicked but not when it's focused by keyboard navigation.

    tooltip(){
  var myElement = document.getElementById("myID");
  let myEvent = "";
  if (myElement=== document.activeElement){
     myEvent = "focus";
  }

return myEvent;
};



<th id="myID" *ngSwitchCase="'validation'" tooltipEvent={{tooltip()}} pTooltip="I am a tooltip"
          tooltipPosition="top" [escape]="false"   [pSortableColumn]="column.field" [ngStyle]="column.style">
            <div class="col-title">
            <span data-testid="column-validationl-header" class="ui-column-title" >Validation </span>
              <p-sortIcon [field]="column.field" *ngIf="column.sortable"></p-sortIcon>
            </div>
          </th>

any Ideas?

2 Answers

Maybe using css :focus selector we can do something.

var stats = document.querySelector("#stats");
var btn = document.querySelector("#btn");
setInterval(function() {
  var test = document.querySelector("#btn:focus");
  stats.innerText = "focused: " + !!test;
}, 50)
<button>dummy</button>
<button>dummy</button>
<button id="btn" style="background:blue">am I focused?</button>
<button>dummy</button>
<div id="stats"></div>

Like the above answer you have to check for the :focus CSS selector. Today you can use the element.matches method

const myElement = document.getElementById("myId");
if (myElement.matches(":focus")) {
  ...
}
Related