Getting the element that has the focus via JavaScript
This is one of those things that you only need on very specific occasions. I needed to get the element that has the focus on a page. Went to Google and found the answer somewhere deep into a forumthread. So for future reference here goes:
Internet Explorer supports the document.activeElement property which gives exactly what I was looking for: the element that has the focus. Because you always have to be careful about javascript properties that are described on a MSDN page, they could be Internet Explorer only, I decided to write a little test to see if it works in the major browsers. I tested this in the following browsers (and corresponding platforms):
- Internet Explorer 6 – Windows
- Internet Explorer 7 – Windows
- Internet Explorer 8 – Windows
- Mozilla Firefox 3.5 – Mac
- Mozilla Firefox 3.5 – Windows
- Google Chrome – Windows (only works for textbox and select elements)
- Safari – Mac (only works for textbox and select elements)
- Safari – Windows (only works for textbox and select elements)
For the Webkit browsers (Safari, Chrome) it appears that the document.activeElement property will only be set if the element that has the focus is a textbox or a select element. Where the other browsers also report if a checkbox or a radiobutton has the focus.
This was my testing HTML file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="c/style.css" media="screen,projection" type="text/css" />
<script src="j/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="j/index.js" type="text/javascript"></script>
</head>
<body>
<input type="text" id="text-box" /><br />
<input type="checkbox" id="checkbox" />
<label for="checkbox">checkbox</label><br />
<select id="select">
<option value="1">Testing</option>
</select><br />
<p>
Current active element: <span id="current-active-element"></span>
</p>
</body>
</html>
With a little bit of javascript attached to it:
$(function()
{
setInterval("updateActiveElement();", 500);
});
function updateActiveElement()
{
$('#current-active-element').text($(document.activeElement).attr('id'));
}
This test page will write out the ID of the active element every 500 milliseconds so we can clearly see which element has the focus.
James Goodfellow has written a post about the property which is now, according to his post, part of the HTML 5 specification. For browsers that don’t support the property, James provides a workaround.