Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding Focus

Status
Not open for further replies.

hc98br

ISP
Aug 14, 2003
46
Question seems simple, just can't find an answer!

I want to test a text field in a form to see if it has focus or not!

Somthing like: if (document.form.text.hasFocus)

Any ideas??


Thanks, Ben
 
event.srcElement will give usually give the element on which the mouse is clicked. therefore if it is empty then the mouse has not been clicked in any element. try it.

or u may have to use a combo of hidden fields and script.
Code:
<input type="text" onfocus='document.FomrName.h1.value=1'>
<input type="hidden" name='h1' value="">

in ur code check if h1's value is 1, if yes then the focus is in the textfield...

Known is handfull, Unknown is worldfull
 
You can set a global var to false:

Code:
var iHaveFocus = false;

...then set your onfocus and onblur events of the field-in-question to change that flag:

Code:
<input type='text' name='textBox' [b]onfocus='iHaveFocus=true' onblur='iHaveFocus=false'[/b] />

Then, check the iHaveFocus var in the function to see if it is true or false.

However, unless you do this check with the body tag's onload event, how do you plan to launch it? If you do it with a button, then the button will have the focus at the time! :)

--Dave
 
Thanks for the prompt reply - shame there is no built in function. I have created a flag, as suggested, which works great!

Cheers


Ben.
 
also i think that if used in a conditional environment element.focus(); will return a true false

like :

if (element.focus()) {alert('yay!');}

[thumbsup2]DreX
aKa - Robert
 
activeElement looks spot-on, but as a Mac Safari user, IE only fuctions put me off!! Lets hope it gets adopted.

DreX, not sure what you mean by conditional enviroment, I originally tried if (element.focus()), and it just set the focus to the element.

Cheers.
 
ok .. guess it doesn't return T/F in a conditional.

thought it might. sorry about the mislead there.

[thumbsup2]DreX
aKa - Robert
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top