Alex Rivera | Logout

Detect which form input has focus using JavaScript or jQuery

Asked 2008-12-10T00:21:07.307
32

How do you detect which form input has focus using JavaScript or jQuery?

From within a function I want to be able to determine which form input has focus. I'd like to be able to do this in straight JavaScript and/or jQuery.

Edit
Report

2 Answers

17

I am not sure if this is the most efficient way, but you could try:

var selectedInput = null;
$(function() {
    $('input, textarea, select').focus(function() {
        selectedInput = this;
    }).blur(function(){
        selectedInput = null;
    });
});
answered 2008-12-10T01:36:26.530
-1

Try

window.getSelection().getRangeAt(0).startContainer
answered 2011-03-21T02:44:02.390

Your Answer