JavaScript – Document.activeElement
JavaScript Document.activeElement property returns the Element of the DOM that currently has focus.
Syntax
The syntax to read activeElement
property of the document is
</>
Copy
document.activeElement
Document.activeElement property is read-only.
Example
In the following example, we have two Textarea elements. When any of these Textarea element is active (in focus), then document.activeElement
property would return that Textarea element. We shall setup a mouseup
event on the Textarea elements, and print the active element in the output.
index.html
</>
Copy
<!DOCTYPE html>
<html lang="en">
<body>
<form>
<textarea id="ta-1" rows="3" cols="30">This is Text Area One.</textarea>
<textarea id="ta-2" rows="3" cols="30">This is Text Area Two.</textarea>
</form>
<p id="output"></p>
<script>
var output = document.getElementById('output');
function printActiveElement(e) {
var activeTextarea = document.activeElement;
var selection = activeTextarea.value.substring(
activeTextarea.selectionStart, activeTextarea.selectionEnd
);
output.innerHTML = 'Active Textarea : #' + activeTextarea.id;
}
var textarea1 = document.getElementById('ta-1');
var textarea2 = document.getElementById('ta-2');
textarea1.addEventListener('mouseup', printActiveElement, false);
textarea2.addEventListener('mouseup', printActiveElement, false);
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt about Document.activeElement property, with examples.