150

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
    }
3
  • 9
    its not a duplicate because the other question asks specifically for a jquery solution. Commented Jun 18, 2017 at 15:10
  • I agree. I wonder if the OP used to be jQuery-based... Commented Nov 13, 2017 at 16:50
  • @HermannIngjaldsson And so implicitly does this, since the code provided uses jQuery (as it did when originally posted). Thus it is a duplicate. Commented Feb 20, 2018 at 0:37

4 Answers 4

376

With pure javascript:

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

or with jquery's :focus pseudo selector.

$(this).is(':focus');
Sign up to request clarification or add additional context in comments.

8 Comments

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..
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;)
thank you for not bringing a jQuery solution. Especially because the pure JS solution is so much shorter too. tips hat
@Mathias - You are probably referring to some obscure definition of 'shorter'...
@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?!
|
2

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

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

Comments

0

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

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.