views:

1207

answers:

3

I'm working on some JavaScript that requires a tag that can get focus. I'd like to be able to use a <div /> tag, however <div /> tags can't get focus.

It looks like the only elements that can gain focus are <input /> tags and <a /> tags. Is there any other way to allow an element to gain focus that isn't an <input /> or <a /> tag?

I can't use <a /> or <input /> tags because I need to be able to place content inside of the tag so neither of those tags will work, unless there's a way to allow nested <a /> tags, although I doubt it since that goes against the standard. I'm trying to figure out a way to allow a <div /> tag (or any other container element) to get focus.

A: 
shahkalpesh
A: 

Somewhat of a workaround and not semantically correct, but...

a#foo { display: block; }
a#foo:hover { cursor: default; }

Then use JavaScript to intercept the onClick event on a#foo and return false.

Mark Hurd
+2  A: 

What do you mean by "can get focus"? Any DOM element can be setup to receive a multitude of javascript events including click events.

Or do you mean "can be tabbed to with the keyboard"? If so, and if you cannot use an a tag as your container, then try the tabindex property on your elements. I'm not sure how cross-browser it is, but at least try it before writing a tabbed ui in javascript yourself.

Crescent Fresh
Any DOM element can receive most events, but not the "focus" event, which seems to be reserved for specific elements which can vary depending on the browser. The "tabindex" property seems to do the trick in my case though.
Dan Herbert
@DanHerbert - curious: what browsers did it work in?
Crescent Fresh