Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find if a textbox is currently selected

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?

like image 404
Leticia Meyer Avatar asked Jan 01 '11 18:01

Leticia Meyer


People also ask

How to find out which textbox is currently selected in javascript?

activeElement , you can check its nodeName. if (document. activeElement. nodeName == 'TEXTAREA' || document.

How to check if textbox is in focus?

Use setFocus() method of textbox to know the textbox is focused or not.

How to check if a textbox is focused in javascript?

How do you know if a textbox has focused? The hasFocus() method returns a true if the document (or any element in the document) has focus.


5 Answers

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

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

Something like that.

like image 60
Thai Avatar answered Nov 08 '22 04:11

Thai


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;

 }

}
like image 44
Leticia Meyer Avatar answered Nov 08 '22 06:11

Leticia Meyer


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)) {
    // …
}
like image 24
Lenar Hoyt Avatar answered Nov 08 '22 05:11

Lenar Hoyt


$('#yourTextAreaID:focus'); 

would not work. :) But

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

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

like image 32
JakeParis Avatar answered Nov 08 '22 06:11

JakeParis


$('#target').focus(function() {
  alert('Handler for .focus() called.');
});

Also Try:

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

http://jsfiddle.net/4KVvV/

like image 1
Naveed Avatar answered Nov 08 '22 06:11

Naveed