8

How would I find if a textbox (or textarea) currently is in focus? I don't care to know which one it is, I just need to know if one is in focus (has the cursor in it). How would I do this with javascript and jquery?

Leticia Meyer
  • 217
  • 2
  • 3
  • 9

5 Answers5

22

Since you have found document.activeElement, you can check its nodeName.

if (document.activeElement.nodeName == 'TEXTAREA' || document.activeElement.nodeName == 'INPUT') {
    // ....
}

Something like that.

Thai
  • 10,746
  • 2
  • 45
  • 57
8

Ok, just figured it out. Here's what I did:

function checkFocus() {

  if ($(document.activeElement).attr("type") == "text" || $(document.activeElement).attr("type") == "textarea") {

  //Something's selected

  return true;

 }

}
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Leticia Meyer
  • 217
  • 2
  • 3
  • 9
  • Someone mark this as the answer, it says I have to wait 2 days. :) – Leticia Meyer Jan 01 '11 at 19:22
  • 2
    you're the only one who *can* mark this as the answer. Also, take a look at the [Stack Overflow Markdown help-page](http://stackoverflow.com/editing-help/), for guidance on how to format your answers, particularly code samples. – David Thomas Jan 01 '11 at 19:22
  • Note that this will work on all modern browsers, but it will *not* work on many outdated browsers. Have a look at [this answer](http://stackoverflow.com/questions/1009777/determining-which-element-has-focus/1009787#1009787) for a technique to overcome this. – lonesomeday Jan 01 '11 at 19:38
3

Extending the accepted answer by a check for editable HTMLDivElements:

if (document.activeElement.nodeName == 'TEXTAREA'
    || document.activeElement.nodeName == 'INPUT'
    || (document.activeElement.nodeName == 'DIV'
        && document.activeElement.isContentEditable)) {
    // …
}
Lenar Hoyt
  • 5,971
  • 6
  • 49
  • 59
2
$('#yourTextAreaID:focus'); 

would not work. :) But

$('#yourTextAreaID').focus(function(){
    // do something
});

would excecute the //do something code when the element receives focus.

JakeParis
  • 11,056
  • 3
  • 42
  • 65
1
$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Also Try:

alert($("*:focus").attr("id"));

http://jsfiddle.net/4KVvV/

Naveed
  • 41,517
  • 32
  • 98
  • 131
  • as @lonesome pointed out above, :hover is not a real jquery selector. I thought it was too, but when I checked the documentation, I couldn't find it mentioned. – JakeParis Jan 02 '11 at 01:53