Javascript question here: How can I determine which text field on a page has focus at any given moment? Ideally with a function like elementWithFocus that with return the html element with focus, but other approcaches are welcome.
I'm using the prototype.js library if that helps in writing the function. But I doubt it would.
People succeed in answering ParagramStudios's questions 26% of the time (9 successes in 34 attempts).
Answers by: Zachary Holt
I don't think there's a function for this. You'll have to keep track yourself.
Javascript:
<script type="text/javascript">
var currentElement;function remember( anElement ) {
currentElement = anElement;
}
function forget( ) {
currentElement = null;
}function elementWithFocus() {
currentElement;
}
</script>
HTML:
<input type="text" onfocus="remember(this);" onblur="forget();">
Note that you will have to check to see whether elementWithFocus is null.
Actually, try this. I think there could be a problem with the firing order of onblur and onfocus of the next element.
Javascript:
<script type="text/javascript">
var currentElement;function remember( anElement ) {
currentElement = anElement;
}
function forget( anElement ) {
if (currentElement == anElement) {
currentElement = null;
}
}function elementWithFocus() {
currentElement;
}
</script>
HTML:
<input type="text" onfocus="remember( this );" onblur="forget( this );">
I'm sorry, I wanted a solution that didn't require any event handlers in the html. And I needed one that would also work with input elements created on the fly with dom scripting. In the end I used an extra invisible input element of type="text" to detect the focus change I was looking for.
Thanks for you attempt it illustrates a way of doing it wih as little code as possible. Just doesn't fit my exact situation.
I wonder if a hasFocus property could be added to input elements of type text and textareas? That would be great.