Javascript/jQuery detect if input is focused

JavascriptJquery

Javascript Problem Overview


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
	}

Javascript Solutions


Solution 1 - Javascript

With pure javascript:

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

or with jquery's :focus pseudo selector.

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

Solution 2 - Javascript

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

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

Solution 3 - Javascript

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

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

Solution 4 - Javascript

Did you try:

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

Take a look at https://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus it features some more examples

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionsouthpaw93View Question on Stackoverflow
Solution 1 - JavascriptPrinzhornView Answer on Stackoverflow
Solution 2 - JavascriptsohaibyView Answer on Stackoverflow
Solution 3 - JavascriptPraveenView Answer on Stackoverflow
Solution 4 - JavascriptVincent CohenView Answer on Stackoverflow