The focus is the interactive element actually active on a HTML dom document through:
Focus indicates the element currently selected (active) that is ready to receive input.
The element with the autofocus=true attribute will be focused after a fetch.
This is generally:
If put on more than one element, the first one with the attribute receives focus .
Example:
function whereIsTheFocus(){
console.log("The active element on this page has");
console.log(" * the id"+parent.document.activeElement.id);
console.log(" * the node name "+parent.document.activeElement.nodeName);
}
console.log("The focus when the page load is");
whereIsTheFocus();
<p>Click on the below button to see the focus changing</p>
<button onClick="whereIsTheFocus()">Where is the focus now ?</button>
With action pseudo class :focus, you can apply style to the focused element.
Example:
textarea:focus {
background-color: aliceblue;
}
<textarea cols="30" rows="5">
Click on me to focus and change the background color
</textarea>
You can modify the focus
document.getElementById("radio-2").focus();
if (element === document.activeElement) {
console.log('focused');
} else {
console.log('not focused');
}
To remove an element from the tab order (focusable by keyboard), set the tabindex to -1 (The element is still focusable by script)
tabindex="-1"
Not all element are by default focusable, only interactive elements (like links, form controls) get focused such as:
To make a non-interactive elements focusable, you need to set the tabindex to a positive value.
When a element gains focus, the focus event is fired.
When a element is focusable, it's passed in the relatedTarget variable of the event.
When the element loose its focus, it's said to blur.
You can track the active element.
/**
* doc is the document
*/
function printActiveElement(active) {
const selector = active.getAttribute('id') ? `#${active.id}` : `${active.localName}.${active.className.replace(/\s/g, '.')}`;
console.log("Active Element Selector: "+selector);
}
parent.window.addEventListener('focusin', e => {
console.log("The active element has changed");
const active = e.target;
printActiveElement(active);
});