views:

59

answers:

4

Is it possible to focus on a <div> using javascript focus() function?

I have a <div> tag

<div id="tries">You have 3 tries left</div>

I am trying to focus on the above <div> using :

document.getElementById('tries').focus();

But it doesn't work. could someone suggest something....?

+4  A: 

Yes - this is possible. In order to do it, you need to assign a tabindex...

<div tabindex="0">Hello World</div>

A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

Sohnee
wow. Is it cross browser?
Mic
And what if in place of <div> tag I am using <td>?
OM The Eternity
But this doesn't bring it to the user's attention, it simply makes it tabable.
Michael Shimmins
@Michael Shimmins, This allows the element to be focusable (in a non-standard way!) with `focus()`.
strager
A: 

To make the border flash you can do this:

function focusTries() {
    document.getElementById('tries').style.border = 'solid 1px #ff0000;'
    setTimeout ( clearBorder(), 1000 );
}

function clearBorder() {
    document.getElementById('tries').style.border = '';
}

This will make the border solid red for 1 second then remove it again.

Michael Shimmins
+1  A: 
window.location.hash = '#tries';

This will scroll to the element in question, essentially "focus"ing it.

Casey Hope
Grt it Worked..... thanks Man
OM The Eternity
A: 

Yes. it posiible. it will fires onFocus handler

Falcon