Baseline Widely available
The activeElement
read-only property of the Document
interface returns the Element
within the DOM that is receiving keyboard events such as keydown
and keyup
. This is usually analogous to the focused element.
Which elements are focusable varies depending on the platform and the browser's current configuration. For example, on Safari, following the behavior of macOS, elements that aren't text input elements are not focusable by default, unless the "Full Keyboard Access" setting is enabled in System Preferences.
Typically a user can press the Tab key to move the focus around the page among focusable elements, and use keyboard gestures such as Space or Enter to simulate clicks on the focused element.
Note: Focus (which element is receiving user input events) is not the same thing as selection (the currently highlighted part of the document). You can get the current selection using window.getSelection()
.
The deepest Element
which currently has focus.
iframe
, and the invoking document
contains that iframe), then this will be the root element of that tree (in this example, that iframe
).document
is an embedded iframe), then this will be null
.Document.body
or Document.documentElement
.<p>Select some text from one of the text areas below:</p>
<form>
<textarea name="ta-example-one" id="ta-example-one" rows="7" cols="40">
This is Text Area One. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.</textarea
>
<textarea name="ta-example-two" id="ta-example-two" rows="7" cols="40">
This is Text Area Two. Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.</textarea
>
</form>
<p>Active element ID: <em id="output-element"></em></p>
<p>Selected text: <em id="output-text"></em></p>
JavaScript
function onMouseUp(e) {
const activeTextarea = document.activeElement;
const selection = activeTextarea.value.substring(
activeTextarea.selectionStart,
activeTextarea.selectionEnd,
);
const outputElement = document.getElementById("output-element");
const outputText = document.getElementById("output-text");
outputElement.textContent = activeTextarea.id;
outputText.textContent = selection;
}
const textarea1 = document.getElementById("ta-example-one");
const textarea2 = document.getElementById("ta-example-two");
textarea1.addEventListener("mouseup", onMouseUp, false);
textarea2.addEventListener("mouseup", onMouseUp, false);
Result Specifications Browser compatibility See also
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3