Internet Explorer has for some time supported giving ‘focus’ to non-focussable elements such as div
s. Firefox, by contrast, does not. Whilst this makes sense semantically, it’s often still very useful to use these triggers. For example, you can use onfocus
to show a popup when a div is clicked, and close the popup when anything else is clicked on the page (in the onblur
event).
There are many, many workarounds which provide this functionality, using such tricks as hidden input elements, global onclick
handlers, and so on, but the simplest is simply this: give your div
a tabIndex
attribute. For example,
[sourcecode language=”html”]
[/sourcecode]
works perfectly in Firefox, Internet Explorer, and Chrome as shown in the example below:
You can also achieve a similar effect purely with CSS:
[sourcecode language=”html”]
[/sourcecode]
Because the second example shows or hides a child element, the parent element will remain focussed if the user interacts with the child element, or its children. This allows you to embed links, forms, videos, and so on in the child element.
The value of tabIndex
can have significance, too:
- -1: The user can’t tab to the element, but it can be given focus programmatically (
element.focus()
) or by being clicked on. - 0: The user can tab to the element, and its order in the tabbing is automatically determined.
- >0: Give the element a priority, with ‘1’ being the highest priority.
I originally discovered this technique on this CodingForums.com thread.
Leave a Reply