how to check if the textbox is in focus in Javascript [duplicate] - javascript
I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how?
The reason I was looking for this:
I'm trying to make keys like the arrows and enter navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
Use document.activeElement, it is supported in all major browsers.
Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field.
If you need to remove the activeElement you can use blur; document.activeElement.blur(). It will change the activeElement to body.
Related links:
activeElement Browser Compatibility
jQuery alternative for document.activeElement
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way:
document.activeElement
It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported by the latest version of Chrome, Safari and Firefox at least.
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+.
This statement will get you the currently focused element.
$(":focus")
From: How to select an element that has focus on it with jQuery
document.activeElement is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector (if that is supported). It's also worth mentioning that document.activeElement will return document.body if no element is focused — even if the browser window doesn't have focus.
The following code will work around this issue and fall back to querySelector giving a little better support.
var focused = document.activeElement;
if (!focused || focused == document.body)
focused = null;
else if (document.querySelector)
focused = document.querySelector(":focus");
An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement property. See this jsperf.com test.
By itself, document.activeElement can still return an element if the document isn't focused (and thus nothing in the document is focused!)
You may want that behavior, or it may not matter (e.g. within a keydown event), but if you need to know something is actually focused, you can additionally check document.hasFocus().
The following will give you the focused element if there is one, or else null.
var focused_element = null;
if (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
) {
focused_element = document.activeElement;
}
To check whether a specific element has focus, it's simpler:
var input_focused = document.activeElement === input && document.hasFocus();
To check whether anything is focused, it's more complex again:
var anything_is_focused = (
document.hasFocus() &&
document.activeElement !== null &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement
);
Robustness Note: In the code where it the checks against document.body and document.documentElement, this is because some browsers return one of these or null when nothing is focused.
It doesn't account for if the <body> (or maybe <html>) had a tabIndex attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow.
Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable.
I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there.
You could also remove the || null part if you don't mind getting false in some cases. (You could still get null if document.activeElement is null):
var focused_element = (
document.hasFocus() &&
document.activeElement !== document.body &&
document.activeElement !== document.documentElement &&
document.activeElement
) || null;
For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state:
var input_focused = false;
input.addEventListener("focus", function() {
input_focused = true;
});
input.addEventListener("blur", function() {
input_focused = false;
});
You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.
document.activeElement may default to the <body> element if no focusable elements are in focus. Additionally, if an element is focused and the browser window is blurred, activeElement will continue to hold the focused element.
If either of these two behaviors are not desirable, consider a CSS-based approach: document.querySelector( ':focus' ).
I have found the following snippet to be useful when trying to determine which element currently has focus. Copy the following into the console of your browser, and every second it will print out the details of the current element that has focus.
setInterval(function() { console.log(document.querySelector(":focus")); }, 1000);
Feel free to modify the console.log to log out something different to help you pinpoint the exact element if printing out the whole element does not help you pinpoint the element.
I liked the approach used by Joel S, but I also love the simplicity of document.activeElement. I used jQuery and combined the two. Older browsers that don't support document.activeElement will use jQuery.data() to store the value of 'hasFocus'. Newer browsers will use document.activeElement. I assume that document.activeElement will have better performance.
(function($) {
var settings;
$.fn.focusTracker = function(options) {
settings = $.extend({}, $.focusTracker.defaults, options);
if (!document.activeElement) {
this.each(function() {
var $this = $(this).data('hasFocus', false);
$this.focus(function(event) {
$this.data('hasFocus', true);
});
$this.blur(function(event) {
$this.data('hasFocus', false);
});
});
}
return this;
};
$.fn.hasFocus = function() {
if (this.length === 0) { return false; }
if (document.activeElement) {
return this.get(0) === document.activeElement;
}
return this.data('hasFocus');
};
$.focusTracker = {
defaults: {
context: 'body'
},
focusedElement: function(context) {
var focused;
if (!context) { context = settings.context; }
if (document.activeElement) {
if ($(document.activeElement).closest(context).length > 0) {
focused = document.activeElement;
}
} else {
$(':visible:enabled', context).each(function() {
if ($(this).data('hasFocus')) {
focused = this;
return false;
}
});
}
return $(focused);
}
};
})(jQuery);
A little helper that I've used for these purposes in Mootools:
FocusTracker = {
startFocusTracking: function() {
this.store('hasFocus', false);
this.addEvent('focus', function() { this.store('hasFocus', true); });
this.addEvent('blur', function() { this.store('hasFocus', false); });
},
hasFocus: function() {
return this.retrieve('hasFocus');
}
}
Element.implement(FocusTracker);
This way you can check if element has focus with el.hasFocus() provided that startFocusTracking() has been called on the given element.
JQuery does support the :focus pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, <!DOCTYPE... must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus:
$(":focus").each(function() {
alert($(this).attr("id") + " has focus!");
});
If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode.
I hope helps.
If you're using jQuery, you can use this to find out if an element is active:
$("input#id").is(":active");
There are potential problems with using document.activeElement. Consider:
<div contentEditable="true">
<div>Some text</div>
<div>Some text</div>
<div>Some text</div>
</div>
If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus.
The following function gets around this, and returns the focused node:
function active_node(){
return window.getSelection().anchorNode;
}
If you would rather get the focused element, use:
function active_element(){
var anchor = window.getSelection().anchorNode;
if(anchor.nodeType == 3){
return anchor.parentNode;
}else if(anchor.nodeType == 1){
return anchor;
}
}
Reading other answers, and trying myself, it seems document.activeElement will give you the element you need in most browsers.
If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand):
if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway
$('*').live('focus', function () { // Attach to all focus events using .live()
document.activeElement = this; // Set activeElement to the element that has been focussed
});
}
With dojo, you can use dijit.getFocus()
Just putting this here to give the solution I eventually came up with.
I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements.
Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was.
It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.
simple use document.activeElement to find the current active element
use document.activeElement.id
appending .id filters out returning the entire DOM and allows you to work only with identified elements
If you want to test the focused element on the dev tools, I suggest using.
$(":focus")
As document.activeElement will change to body when you click on anything in the dev tool.
To get the previous active element add this.
Example: you click on a button and need the previous active element. Since the button gets the focus once click on it.
document.addEventListener("focusout",ev => {
document.previousActiveElement = ev.target;
});
Related
how to use Jquery :focus selector on input elements in iOS?
I'm using Jquery 1.7.1 and iPad1 iOS3. I need to fire a function on scrollstart unless an input element has focus. The function below worked for a long time, but all of a sudden it doesn't (looking aroud I guess because of switching to Jquery 1.7.1) $(document).on('scroll', function(){ if ( !$("input:focus").length > 0 ) { self.hideAllPanels(); } }); Specifically $('input:focus').length = 0, although I can detect the focus event triggering before the scroll event. I have been fiddling with a workaround using: if ( !$(document.activeElement).get(0).tagName == "input" ){ .... } But I'm not sure when the activeElement is changing, because it seems to persist for quite a while even after I'm "leaving" the resprective element. Question: Any idea why I can't detect the focus-ed element on iOS? Some hints how I could set this up with activeElement, so on blur, I'm no longer having the input as activeElement are also welcome! Thanks for help!
$(document).on('scroll', function(){ if (!$("input").is(':focus')) { self.hideAllPanels(); } }); This seems to work for me, but it will fire the function multiple times during scroll if an input element does not have focus.
How to determine where focus went?
This has been asked here before, but several years ago, and there was no cross-platform solution at the time (other than the setTimeout solution, which is really not very handy). I'd like to do onblur="foo(parm);" and have foo be able to determine which element now has focus. I'm using regular javascript; no jQuery for this one, please. Is that possible these days?
You can try something like this: function whereDidYouGo() { var all = document.getElementsByTagName('*'); for (var i = 0; i < all.length; i++) if (all[i] === all[i].ownerDocument.activeElement) return all[i]; } EDIT: function whereDidYouGo() { return document.activeElement; }
In jQuery, at the OP's request: $(':input').blur(function() { $focusedElement = $(':input:focus'); //Do stuff with $focusedElement }
Interesting question. The heart of the matter is - when does the 'focus' event fire, before or after the blur event? If it fires before the blur event, the problem is easy, because you can just store the current focus in a variable that your blur event can access. However, at least in Chrome 13, it appears the blur event happens before the focus event. One possible solution. Given the following HTML: <input id="foo" value='foo' /> <input id="bar" value='bar' /> You can then: var currentFocus; var pendingBlur; var foo = document.getElementById('foo'); foo.addEventListener('focus', function(){ currentFocus = foo; if(pendingBlur !== undefined){ pendingBlur(); pendingBlur = undefined; } }); foo.addEventListener('blur', function(){ pendingBlur = function(){ console.log('new focus:', currentFocus); }; }); var bar= document.getElementById('bar'); bar.addEventListener('focus', function(){ currentFocus = bar; if(pendingBlur !== undefined){ pendingBlur(); pendingBlur = undefined; } }); bar.addEventListener('blur', function(){ pendingBlur = function(){ console.log('new focus:', currentFocus); }; }); Basically, I just not the blur callback so it is handy for the focus event to call after we know about which element was focused. Here is a working example on JSFiddle. EDIT: This solution suffers from the problem that if you blur on the form by clicking on something other than another form element, the blur event never fires (since we wait for the focus event). The only way around that, that I can conceive, is using a timer to check if pendingBlur is defined, and if so, call it. At which point you don't really need the focus event to call the blur callback anymore...
Year 2020: All major browsers (desktop and mobile) support FocusEvent.relatedTarget.
event.relatedTarget couldn't find the newly-focused element(was div type in my case), but only null gets returned. After attaching the attribute tabindex="0" on the element, now it works. <div id="myDiv">myDiv</div> console.log(e.relatedTarget) // null <div id="myDiv" tabindex="0"> tabindexed div </div> console.log(e.relatedTarget) // <div id="myDiv" tabindex="0"> tabindex is an attribute that make elements focusable using tab key on keyboard. I guess it is mainly for web accessibility. And I guess you won't need to set tabindex attribute as long as to-be focused elements are already accessible by tab key (such as a, select.. and so on)
Retrieving previously focused element
I would like to find out, in Javascript, which previous element had focus as opposed to the current focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this any help would be much appreciated
Each time an element is focused, you'd have to store which one it was. Then when another element is focused, you could retrieve the variable for the previous focused element. So basically, your single focus handler would do 2 things: Check if previousFocus is defined. If it is, retrieve it. Set previousFocus to the currently focused element. Here is a quick demo with jQuery (you can use raw JS too... just fewer lines w jQuery, so it's easier to understand imo): // create an anonymous function that we call immediately // this will hold our previous focus variable, so we don't // clutter the global scope (function() { // the variable to hold the previously focused element var prevFocus; // our single focus event handler $("input").focus(function() { // let's check if the previous focus has already been defined if (typeof prevFocus !== "undefined") { // we do something with the previously focused element $("#prev").html(prevFocus.val()); } // AFTER we check upon the previously focused element // we (re)define the previously focused element // for use in the next focus event prevFocus = $(this); }); })(); working jsFiddle
Just found this question while solving the exact same problem and realised it was so old the jQuery world has moved on a bit :) This should provide a more effective version of Peter Ajtais code, as it will use only a single delegated event handler (not one per input element). // prime with empty jQuery object window.prevFocus = $(); // Catch any bubbling focusin events (focus does not bubble) $(document).on('focusin', ':input', function () { // Test: Show the previous value/text so we know it works! $("#prev").html(prevFocus.val() || prevFocus.text()); // Save the previously clicked value for later window.prevFocus = $(this); }); JSFiddle: http://jsfiddle.net/TrueBlueAussie/EzPfK/80/ Notes: Uses $() to create an empty jQuery object (allows it to be used immediately). As this one uses the jQuery :input selector it works with select & button elements as well as inputs. It does not need a DOM ready handler as document is always present. As the previously focused control is required "elsehere" is is simply stored on window for global use, so it does not need an IIFE function wrapper.
Well depending on what else your page is doing, it could be tricky, but for starters you could have a "blur" event handler attached to the <body> element that just stashes the event target.
To me this seems a slight improvement on Gone Coding's answer: window.currFocus = document; // Catch focusin $(window).on( 'focusin', function () { window.prevFocus = window.currFocus; console.log( '£ prevFocus set to:'); console.log( window.currFocus ); window.currFocus = document.activeElement; }); ... there's no stipulation in the question that we're talking exclusively about INPUTs here: it says "previous elements". The above code would also include recording focus of things like BUTTONs, or anything capable of getting focus.
document.getElementById('message-text-area').addEventListener('focus', event => console.log('FOCUS!') ); event.relatedTarget has all the data about the previously focused element. See also https://developer.mozilla.org/en-US/docs/Web/API/Event/Comparison_of_Event_Targets
Here is a slightly different approach which watches both focusin and focusout, in this case to prevent focus to a class of inputs: <input type="text" name="xyz" value="abc" readonly class="nofocus"> <script> $(function() { var leaving = $(document); $(document).on('focusout', function(e) { leaving = e.target; }); $( '.nofocus' ).on('focusin', function(e) { leaving.focus(); }); $( '.nofocus' ).attr('tabIndex', -1); }); </script> Setting tabIndex prevents keyboard users from "getting stuck".
window.event.srcElement doesn't work for firefox?
The following doesn't work for firefox. I'm trying delete the table row on click. Can anyone please help. Many thanks. <INPUT TYPE="Button" onClick="delRow()" VALUE="Remove"> function delRow(){ if(window.event){ var current = window.event.srcElement; }else{ var current = window.event.target; } //here we will delete the line while ( (current = current.parentElement) && current.tagName !="TR"); current.parentElement.removeChild(current); }
window.event is IE only. window.event does not exist in W3C standard. event object by default is pass in as the first argument to a event handler with the W3C standard. an inline onlick event in the markup calling a function mean that the event handler is calling that function. With your markup as example. It mean function() { delRow(); }. As you can see you won't be able to see the event object in delRow() except when you are in IE because event is in the window object. parentElement is also IE only, in most case changing it to parentNode would work. Assuming the parent node is also an element. I suggest you to use javascript library such as jQuery or change your code if you need to keep things relatively the same. <INPUT TYPE="Button" onclick="delRow(event);" VALUE="Remove"> function delRow(e) { var evt = e || window.event; // this assign evt with the event object var current = evt.target || evt.srcElement; // this assign current with the event target // do what you need to do here }
You have to use event.target instead of window.event.target to work for Firefox. Try to use the following. <INPUT TYPE="Button" onclick="delRow()" VALUE="Remove"> function delRow(){ if(window.event){ var current = window.event.srcElement; }else{ current = event.target; } //here we will delete the line while ( (current = current.parentElement) && current.tagName !="TR"); current.parentElement.removeChild(current); }
var CurrentObject = 0 < window.navigator.appVersion.toString().indexOf("MSIE") ? window.event.srcElement : evt.target;
Here's Mozilla's documentation of the Event class; might give you some insight.
NEVER use individual browser checks like "check for MSIE". Do you know how many browsers you'd have to check for... and individual browser VERSIONS... to check them all? NEVER use jQuery for this either. Write correct code yourself. Never include (useless) massive libraries when you aren't going to use 99% of their features anyway.
just found out, works on ie & ff and chrome. others don't know but I expect that this will work on allso the rest. at least hope so :) As a beginner in html, JS and PHP, it's very annoying that there is not a standard in these things ! even styling a simple div element can be a headage because of the behavior is not allways the same on different browsers !? function somefunc() { var callerelement = arguments.callee.caller.arguments[0].target; alert(callerelement.id) }
How do I find out which DOM element has the focus?
I would like to find out, in JavaScript, which element currently has focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this, and how? The reason I was looking for this: I'm trying to make keys like the arrows and enter navigate through a table of input elements. Tab works now, but enter, and arrows do not by default it seems. I've got the key handling part set up but now I need to figure out how to move the focus over in the event handling functions.
Use document.activeElement, it is supported in all major browsers. Previously, if you were trying to find out what form field has focus, you could not. To emulate detection within older browsers, add a "focus" event handler to all fields and record the last-focused field in a variable. Add a "blur" handler to clear the variable upon a blur event for the last-focused field. If you need to remove the activeElement you can use blur; document.activeElement.blur(). It will change the activeElement to body. Related links: activeElement Browser Compatibility jQuery alternative for document.activeElement
As said by JW, you can't find the current focused element, at least in a browser-independent way. But if your app is IE only (some are...), you can find it the following way: document.activeElement It looks like IE did not have everything wrong after all, this is part of HTML5 draft and seems to be supported by the latest version of Chrome, Safari and Firefox at least.
If you can use jQuery, it now supports :focus, just make sure you are using version 1.6+. This statement will get you the currently focused element. $(":focus") From: How to select an element that has focus on it with jQuery
document.activeElement is now part of the HTML5 working draft specification, but it might not yet be supported in some non-major/mobile/older browsers. You can fall back to querySelector (if that is supported). It's also worth mentioning that document.activeElement will return document.body if no element is focused — even if the browser window doesn't have focus. The following code will work around this issue and fall back to querySelector giving a little better support. var focused = document.activeElement; if (!focused || focused == document.body) focused = null; else if (document.querySelector) focused = document.querySelector(":focus"); An addition thing to note is the performance difference between these two methods. Querying the document with selectors will always be much slower than accessing the activeElement property. See this jsperf.com test.
By itself, document.activeElement can still return an element if the document isn't focused (and thus nothing in the document is focused!) You may want that behavior, or it may not matter (e.g. within a keydown event), but if you need to know something is actually focused, you can additionally check document.hasFocus(). The following will give you the focused element if there is one, or else null. var focused_element = null; if ( document.hasFocus() && document.activeElement !== document.body && document.activeElement !== document.documentElement ) { focused_element = document.activeElement; } To check whether a specific element has focus, it's simpler: var input_focused = document.activeElement === input && document.hasFocus(); To check whether anything is focused, it's more complex again: var anything_is_focused = ( document.hasFocus() && document.activeElement !== null && document.activeElement !== document.body && document.activeElement !== document.documentElement ); Robustness Note: In the code where it the checks against document.body and document.documentElement, this is because some browsers return one of these or null when nothing is focused. It doesn't account for if the <body> (or maybe <html>) had a tabIndex attribute and thus could actually be focused. If you're writing a library or something and want it to be robust, you should probably handle that somehow. Here's a (heavy airquotes) "one-liner" version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y'know, it obviously doesn't fit on one line, assuming you want it to be readable. I'm not gonna recommend this one. But if you're a 1337 hax0r, idk... it's there. You could also remove the || null part if you don't mind getting false in some cases. (You could still get null if document.activeElement is null): var focused_element = ( document.hasFocus() && document.activeElement !== document.body && document.activeElement !== document.documentElement && document.activeElement ) || null; For checking if a specific element is focused, alternatively you could use events, but this way requires setup (and potentially teardown), and importantly, assumes an initial state: var input_focused = false; input.addEventListener("focus", function() { input_focused = true; }); input.addEventListener("blur", function() { input_focused = false; }); You could fix the initial state assumption by using the non-evented way, but then you might as well just use that instead.
document.activeElement may default to the <body> element if no focusable elements are in focus. Additionally, if an element is focused and the browser window is blurred, activeElement will continue to hold the focused element. If either of these two behaviors are not desirable, consider a CSS-based approach: document.querySelector( ':focus' ).
I have found the following snippet to be useful when trying to determine which element currently has focus. Copy the following into the console of your browser, and every second it will print out the details of the current element that has focus. setInterval(function() { console.log(document.querySelector(":focus")); }, 1000); Feel free to modify the console.log to log out something different to help you pinpoint the exact element if printing out the whole element does not help you pinpoint the element.
I liked the approach used by Joel S, but I also love the simplicity of document.activeElement. I used jQuery and combined the two. Older browsers that don't support document.activeElement will use jQuery.data() to store the value of 'hasFocus'. Newer browsers will use document.activeElement. I assume that document.activeElement will have better performance. (function($) { var settings; $.fn.focusTracker = function(options) { settings = $.extend({}, $.focusTracker.defaults, options); if (!document.activeElement) { this.each(function() { var $this = $(this).data('hasFocus', false); $this.focus(function(event) { $this.data('hasFocus', true); }); $this.blur(function(event) { $this.data('hasFocus', false); }); }); } return this; }; $.fn.hasFocus = function() { if (this.length === 0) { return false; } if (document.activeElement) { return this.get(0) === document.activeElement; } return this.data('hasFocus'); }; $.focusTracker = { defaults: { context: 'body' }, focusedElement: function(context) { var focused; if (!context) { context = settings.context; } if (document.activeElement) { if ($(document.activeElement).closest(context).length > 0) { focused = document.activeElement; } } else { $(':visible:enabled', context).each(function() { if ($(this).data('hasFocus')) { focused = this; return false; } }); } return $(focused); } }; })(jQuery);
A little helper that I've used for these purposes in Mootools: FocusTracker = { startFocusTracking: function() { this.store('hasFocus', false); this.addEvent('focus', function() { this.store('hasFocus', true); }); this.addEvent('blur', function() { this.store('hasFocus', false); }); }, hasFocus: function() { return this.retrieve('hasFocus'); } } Element.implement(FocusTracker); This way you can check if element has focus with el.hasFocus() provided that startFocusTracking() has been called on the given element.
JQuery does support the :focus pseudo-class as of current. If you are looking for it in the JQuery documentation, check under "Selectors" where it points you to the W3C CSS docs. I've tested with Chrome, FF, and IE 7+. Note that for it to work in IE, <!DOCTYPE... must exist on the html page. Here is an example assuming you've assigned an id to the element that has focus: $(":focus").each(function() { alert($(this).attr("id") + " has focus!"); });
If you want to get a object that is instance of Element, you must use document.activeElement, but if you want to get a object that is instance of Text, you must to use document.getSelection().focusNode. I hope helps.
If you're using jQuery, you can use this to find out if an element is active: $("input#id").is(":active");
There are potential problems with using document.activeElement. Consider: <div contentEditable="true"> <div>Some text</div> <div>Some text</div> <div>Some text</div> </div> If the user focuses on an inner-div, then document.activeElement still references the outer div. You cannot use document.activeElement to determine which of the inner div's has focus. The following function gets around this, and returns the focused node: function active_node(){ return window.getSelection().anchorNode; } If you would rather get the focused element, use: function active_element(){ var anchor = window.getSelection().anchorNode; if(anchor.nodeType == 3){ return anchor.parentNode; }else if(anchor.nodeType == 1){ return anchor; } }
Reading other answers, and trying myself, it seems document.activeElement will give you the element you need in most browsers. If you have a browser that doesn't support document.activeElement if you have jQuery around, you should be able populate it on all focus events with something very simple like this (untested as I don't have a browser meeting those criteria to hand): if (typeof document.activeElement === 'undefined') { // Check browser doesn't do it anyway $('*').live('focus', function () { // Attach to all focus events using .live() document.activeElement = this; // Set activeElement to the element that has been focussed }); }
With dojo, you can use dijit.getFocus()
Just putting this here to give the solution I eventually came up with. I created a property called document.activeInputArea, and used jQuery's HotKeys addon to trap keyboard events for arrow keys, tab and enter, and I created an event handler for clicking into input elements. Then I adjusted the activeInputArea every time focus changed, so I could use that property to find out where I was. It's easy to screw this up though, because if you have a bug in the system and focus isn't where you think it is, then its very hard to restore the correct focus.
simple use document.activeElement to find the current active element
use document.activeElement.id appending .id filters out returning the entire DOM and allows you to work only with identified elements
If you want to test the focused element on the dev tools, I suggest using. $(":focus") As document.activeElement will change to body when you click on anything in the dev tool.
To get the previous active element add this. Example: you click on a button and need the previous active element. Since the button gets the focus once click on it. document.addEventListener("focusout",ev => { document.previousActiveElement = ev.target; });