To find the DOM element that has the focus:
Code Example:
var focusedElement = document.activeElement;
console.log(focusedElement);
You can also use document.hasFocus() to check if the document has focus or not.
console.log(document.hasFocus());
You may also use document.body.contains(document.activeElement) to check if the active element is in the body or not.
console.log(document.body.contains(document.activeElement));
Print element in the console window when focused
You can also attach an event listener to the document object and listen for the focus and blur events to detect when an element receives and loses focus.
document.addEventListener("focus", function(event) {
console.log(event.target);
}, true);
0 Comments