How to receive focus on elements that doesn’t by default support focus or simply how to make them support onFocus event[HTML]

The following elements by default support focus:

  • HTMLAnchorElement, HTMLAreaElement with an href
  • HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement, HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
  • HTMLIFrameElement (though focusing it doesn’t do anything useful). Other embedding elements also, maybe.

And hence these support the onFocus() event too.

But you can achieve this functionality on elements that doesn’t receive focus by default, with a trick.

You need tabIndex property to be set for these elements.

E.g. a <div> element doesn’t support focus by default. See the DEMO or the code below:

<div onfocus="try{alert('div1 focused'); blur();} catch(e){alert(e)}">abc</div>
<div onfocus="try{alert('div2 focused'); blur();} catch(e){alert(e)}">def</div>

Now to allow focus on the divs you need to set their tabIndex property with numeric values. Check this DEMO or the code below:

<div tabIndex=1 onfocus="try{alert('div1 focused'); blur();} catch(e){alert(e)}">abc</div>
<div tabIndex=2 onfocus="try{alert('div2 focused'); blur();} catch(e){alert(e)}">def</div>

N.B. The elements that doesn’t support focus allow onClick, but onClick occurs when the element is clicked but in case a user wants to navigate using TAB-key then onclick can’t serve your need. Then you must use onFocus to keep track of user activity.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s