» Find out which HTML element has focus using JavaScript
Posted by Kasper Tidemann on Tuesday 5th of January 2010 04:35:55 AM
If you need to know which element on your HTML page has the current focus, you can use the document.activeElement attribute recently introduced in all the major browsers (it works in Firefox 3, Safari 4, Internet Explorer 8 etc.).
For example, this is very useful if you need to determine whether an input field has focus or not. You might have a user typing stuff in a form, and you do not wish for the user to leave the page (by mistake) in the middle of typing text in one of your input fields.
As an example of the use of document.activeElement, have a look at the following piece of code:
<html>
<head>
<title>My test page</title>
<script type="text/javascript">
window.onkeypress = getActiveHTMLElement;
function getActiveHTMLElement(keyevent) {
keyevent = (keyevent) ? keyevent : ((window.event) ? event : null);
if (keyevent) {
switch (keyevent.keyCode) {
case 8:
alert(document.activeElement.tagName);
break;
}
}
}
</script>
</head>
<body>
This is my test page. Now, press backspace!
</body>
</html>
The above code will return the tag name of the element that has focus each time you press the backspace button on the page.
The document.activeElement attribute is a part of the coming HTML 5 specification. For more info, please click here and read up on the changes to come.





