149

How do I detect when .click event triggers if textarea is already focused?

I have this jquery:

$(".status").on("click","textarea",function(){
        if ($(this) == "focused") {
            // fire this step
        }else{
            $(this).focus();
            // fire this step
    }
southpaw93
  • 1,891
  • 5
  • 22
  • 39

4 Answers4

374

With pure javascript:

this === document.activeElement // where 'this' is a dom object

or with jquery's :focus pseudo selector.

$(this).is(':focus');
B T
  • 57,525
  • 34
  • 189
  • 207
Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
  • 2
    I don't know why it is not working.... none of them.. if it's not focused it fires the first step.. but it should fire the else step.. – southpaw93 Jul 12 '13 at 12:39
  • 1
    Clicking the textarea will alway focus it. – Prinzhorn Jul 12 '13 at 13:34
  • 5
    Note that setting focus with 'focus()' won't work if the node isn't attached to the dom or is hidden (e.g. display:none;) – B T Apr 25 '14 at 21:03
  • 38
    thank you for not bringing a jQuery solution. Especially because the pure JS solution is so much shorter too. *tips hat* – Mathias Dec 16 '14 at 23:59
  • 11
    @Mathias - You are probably referring to some obscure definition of 'shorter'... – katzenhut Nov 24 '16 at 09:41
  • 12
    @katzenhut ha, yeah ... not sure what I was trying to say (back in 2014). I assume I meant 'shorter' as in, doesn't invoke a bunch of library code?! – Mathias Nov 28 '16 at 23:50
  • Seems there's now a :focus pseudo-selector. So `document.querySelector('textarea:focus')` will return the textarea element that is in focus, or the usual `null` if there isn't one. – Aaron Mason Mar 09 '20 at 00:01
  • The above seems to work on Chrome, but if you're developing with Cordova, you might find this doesn't work on iOS devices. – Aaron Mason Mar 09 '20 at 02:51
1

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');
sohaiby
  • 1,168
  • 3
  • 24
  • 39
0

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }
Praveen
  • 55,303
  • 33
  • 133
  • 164
0

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

Community
  • 1
  • 1
Vincent Cohen
  • 878
  • 7
  • 28