views:

233

answers:

3

I want to catch which element is on focus when users use tab key to move their focus. For example, there is a form and users can use tab key to move forward to next form element. I'd like to know which element is the current on focus.

Thanks, Paul

A: 

there are javascript events that are related to focus. The onfocus and onblur (opposite of focus) events can be used to update a variable that says which form element is currently in focus.

barkmadley
+1  A: 

use the onFocus event on the form elements, so

<form>
   <input id="fred" type="text" onFocus="alert('focused this');"/>
</form>

check out http://www.w3.org/TR/html4/interact/scripts.html#adef-onfocus

pmc
+1  A: 

For many event types one can use event delegation, whereby one captures the event on some containing element as it bubbles up the document hierarchy, and then establishes the element on which the event originated. Unfortunately, the focus, blur, and change events do not bubble.

However, in DOM implementations that implement the standard DOM Events model, one can instead use the capture phase, which intercepts the event on its way down to the element where it will fire.

This doesn't work in (surprise, surprise) Internet Explorer (IE), which still doesn't have an implementation of the standard event model, even in IE8. However, IE has its own focusin and focusout events, which do bubble.

The end result is that, as usual, one has to write one's code so as to deal with the way proper browsers work, and also with the way IE works.

Luckily this is one of those cases where ppk (aka Peter-Paul Koch) of quirksmode.org has already done the hard work: his article Delegating the focus and blur events should tell you all you need to know, as well as providing a succinct explanation of how event delegation works.

NickFitz