Javascript/jQuery detect if input is focused [duplicate]
Asked Answered
C

4

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
    }
Croupier answered 12/7, 2013 at 12:23 Comment(3)
its not a duplicate because the other question asks specifically for a jquery solution.Urbana
I agree. I wonder if the OP used to be jQuery-based...Melanimelania
@HermannIngjaldsson And so implicitly does this, since the code provided uses jQuery (as it did when originally posted). Thus it is a duplicate.Ruse
K
375

With pure javascript:

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

or with jquery's :focus pseudo selector.

$(this).is(':focus');
Keir answered 12/7, 2013 at 12:25 Comment(8)
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..Croupier
Clicking the textarea will alway focus it.Keir
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;)Cachet
thank you for not bringing a jQuery solution. Especially because the pure JS solution is so much shorter too. tips hatBluegill
@Bluegill - You are probably referring to some obscure definition of 'shorter'...Emaciation
@Emaciation 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?!Bluegill
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.Sebbie
The above seems to work on Chrome, but if you're developing with Cordova, you might find this doesn't work on iOS devices.Sebbie
Z
2

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

$(this).is(':focus');
Zagreb answered 12/7, 2013 at 12:26 Comment(0)
N
0

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

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }
Nye answered 12/7, 2013 at 12:25 Comment(0)
R
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

Rayfordrayle answered 12/7, 2013 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.