I can’t seem to get the currently focused/active element as a jQuery object in Firefox, if it is an <input type="file" />. It works on other input types (text, password, submit, others) and on other element types (<select>, <textarea>, others).
HTML
<input type="file" />
Javascript
// Cannot find input type file elements with :focus,
// $focused.length is always 0 in Firefox (tested using FF 10.0.1)
var $focusedTest1 = $(':focus');
// This line throws for Firefox (tested using FF 10.0.1)
// Permission denied to access property 'nodeType'
// @ http://code.jquery.com/jquery-1.7.1.js:108
// in jQuery.fn.init, below "Handle $(DOMElement)"
var $focusedTest2 = $(document.activeElement);
Steps to reproduce
- Use Firefox.
- Focus the file box:
- press tab until you reach it
- or click in it.
- While focusing the file box, try to get a result from
$(':focus').
See jsFiddle demonstration of getting the id of the focused element – test it with Firefox.
Does anyone have a solution for getting the focused/active element as a jQuery object that works for <input type="file" />?
The solution needs to be fully generic as the functionality is part of a plugin. I will not have control over the page the script will run on.
Edit: This solution has been implemented where the problem was first found, in EmulateTab. See getFocusedElement().
Found a solution myself, after a break from coding – but it is not a very clean solution. It is basically the same solution suggested by @Neil while I first wrote this post.
Try the updated jsFiddle version with focus listeners and try-catch logic in Firefox. It combines
:focus,document.activeElementand document level focus listeners that keep track of the last “known” focused element.Function to find focused element
Focus listeners
I don’t like this solution very much, as it is far from as clean as just a one-line
$(':focus'). Other answers are welcome!