How can I tell if a certain textbox has focus or not? I'm writing in C# in .NET.
Asked
Active
Viewed 2,659 times
-2
-
duplicate : http://stackoverflow.com/questions/483741/how-to-determine-which-html-page-element-has-focus – Russ Cam Oct 07 '09 at 17:06
-
The 'javascript' tag might be a mistake, but this is not a duplicate of the above question IMHO. – RedGlyph Oct 07 '09 at 17:28
-
1redglyph: Check the edit history, he originally said "I'm using javascript writing in C#.NET" – Erich Oct 07 '09 at 17:42
-
Alright, thanks for pointing that out, it was confusing. And apparently now it's Javascript anyway from the last comment, ah well ;) – RedGlyph Oct 07 '09 at 18:40
2 Answers
4
You would have to use the javascript events OnFocus
and OnBlur
, and set a variable of some sort. Basically:
<script>
var lastFocus=null;
function DoesControlHaveFocus(var control){return control==lastFocus;}
</script>
<input type="text" onfocus="lastFocus=this" onblur="lastFocus=null"/>
FOR A version that would work in the code-behind, you would set a hidden field to the ID of the control in the OnFocus command, which you could then check.

Erich
- 3,946
- 1
- 22
- 21
-
I think this will be my answer. I didn't get a chance to try it though but it seems right. +1 to you. – Eric Oct 07 '09 at 17:44
3
Because performance can be a problem with generic solutions, the easiest thing I've come across so far is as follows:
- Subscribe to the onFocus event of each control you care about.
- In the onFocus handler, set a global variable (maybe "lastFocusElement") to the element that just received focus.
- When you need to know that a certain control has focus, compare against the "lastFocusElement" variable.

John Fisher
- 22,355
- 2
- 39
- 64
-
Here, for C#, I have the `Enter` event actually, not onFocus (and the OnEnter Method). But that's the idea, I usually do that when I need to keep track of the focused element and it works fine. – RedGlyph Oct 07 '09 at 17:30