Is there a way with javascript to see if a form input has focus? I know I can use onblur and onfocus events and keep track of it with a variable, but those are not as reliable.
| SitePoint Sponsor |



Is there a way with javascript to see if a form input has focus? I know I can use onblur and onfocus events and keep track of it with a variable, but those are not as reliable.


I had trouble determining select option focus, but with other inputs something like this should work
if(document.formid.inputid.focus == true)//do stuff



Hmm, I always thought using a method without the brackets returned true if the function was availible and false if not. I will give it a try.


If it's only 1 statement you can leave the brackets out. It's more of a preference. Using them doesn't hurt if you're more comfortable reading your script with them. These are equivalent.
PHP Code:if(1 == 1) echo "hey";
PHP Code:if(1 == 1){
echo "hey";
}
focus() is a method to give an element focus. You can't use that for this.
IE has the activeElement property for this, but other browsers don't have a similar property.
We miss you, Dan Schulz.
Learn CSS. | X/HTML Validator | CSS validator
Dynamic Site Solutions
Code for Firefox, Chrome, Safari, & Opera, then add fixes for IE, not vice versa.


@Kravvitz, right you are. And I would've bet it was a property and a method. I guess using an event handler is the way to go, reliable or not.



My mistake, I meant parentheses (). If you leave the parentheses off of a function in JavaScript, it returns 'undefined' if the function is not defined, or something like this: 'function focus() { [native code] }'. See quriksmode for a good article on this.Originally Posted by Mittineague
I guess I will resort to using the events.
Bookmarks