Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a reference to the currently focused form field in JavaScript?

Tags:

I'm looking for a cross-browser method - I know IE has something (I've already forgotten what), and the way to do it in Mozilla may have to do with a focusNode thing I found, that seems related to getting text selections.

Methods involving jQuery or another common JS library are fine by me.

Thanks!

like image 1000
misuba Avatar asked Sep 30 '08 00:09

misuba


2 Answers

Check out the extra selectors plugin for jQuery, it includes a :focus selector that answers your need. You can use just the implementation of that selector if you don't the rest.

like image 80
Eran Galperin Avatar answered Sep 30 '22 17:09

Eran Galperin


OK then, so use jQuery.

There is no current, available way to just ask this. You need to track the focus events when they happen, so this sample (thanks to Karl Rudd here) does that across all elements. This is for inputs but you can adjust the selector to fit your needs, even across the entire DOM.

var currentFocus = null; 
$(':input').focus( function() { 
    currentFocus = this; 
}).blur( function() { 

    currentFocus = null; 
}); 
like image 43
ironfroggy Avatar answered Sep 30 '22 15:09

ironfroggy