4

I'm working on keyboard accessibility. I have a flash object which sits inside a page, and to stop the focus getting trapped inside it, I've added tab listeners which talk through ExternalInterface to some JavaScript functions.

The JavaScript looks for the next available element with a tabIndex and calls focus() on it. So far so good. But if the plugin is the last tabbable item on the page (or first when reverse-tabbing), there is no element to switch to. Normally this would set focus to the browser window, so I'd like to keep that behaviour.

Hence my question: Is it possible to programatically give focus to the browser's chrome? Even better if I can mimic both forward and backward tabbing. Also I'd like to avoid adding extra tabbable components before/after the flash if possible, unless I can make them effectively invisible to both the mouse and keyboard.

Dave
  • 44,275
  • 12
  • 65
  • 105

2 Answers2

3

Came across this in my own search for a similar answer. If you want to release the focus on the currently focused element, use document.activeElement; If you want a fallback in the off chance its not supported, use focus on the parent element of the document. This should support all known browsers, as far as I know:

var activeElement = document.activeElement;
if (activeElement) {
   activeElement.blur();
} else if (document.parentElement) {
   document.parentElement.focus();
} else {
   window.focus();
}
JDL
  • 1,477
  • 21
  • 31
0

Setting the focus to a dummy anchor with no text content, at the top of the document, seems to work:

document.getElementsByTagName('a')[0].focus();

http://jsfiddle.net/4NA5u/1/.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • As I said, I'd like to avoid adding extra tabbable components unless they can be made invisible to the keyboard; this way means that users need to press tab an extra time to get past. So I'll wait to see if anybody has another way. – Dave Apr 05 '13 at 20:03
  • Well nobody's had a better idea, so I'm going with this for now. – Dave Apr 06 '13 at 12:34
  • How about giving focus to any focuseable element, and immediately blurring it? – bfavaretto Apr 06 '13 at 21:57
  • I suppose the final effect is removing focus from te flash movie. – bfavaretto Apr 06 '13 at 22:08