Coder Perfect

What is the best way to see if my Element ID has focus? [duplicate]

Problem

Assume I have the following div that receives focus when a specific condition is met:

<div id="myID" tabindex="-1" >Some Text</div>

When it evaluates to true/focus is on the div, do something (in the example below, print a console log): I want to develop a handler that checks whether or not that div has focus, and when it evaluates to true/focus is on the div, do something (in the example below, print a console log):

if (document.getElementById('#myID').hasFocus()) {
            $(document).keydown(function(event) {
                if (event.which === 40) {
                    console.log('keydown pressed')
                }
            });
        }

In the console, I’m getting an error message that says:

TypeError: The null property ‘hasFocus’ cannot be read.

I’m not sure what I’m doing wrong. Maybe it’s because of the manner I’m passing the div Id?

Asked by Kode_12

Solution #1

Compare the two documents. use activeElement to check for focus on the element you want to check. The element is focused if they are the same; otherwise, it isn’t.

// dummy element
var dummyEl = document.getElementById('myID');

// check for focus
var isFocused = (document.activeElement === dummyEl);

hasFocus is a document-level method; DOM elements don’t have one.

Also, myID is not preceded by a # in document.getElementById. This should be changed:

var dummyEl = document.getElementById('#myID');

to this:

var dummyEl = document.getElementById('myID');

You can use querySelector instead if you want to utilize a CSS query (and querySelectorAll).

Answered by Florrie

Solution #2

Use document.activeElement

Should work.

P.S. getElementById(“myID”), not getElementById(“#myID”), is the correct syntax.

Answered by Oen44

Solution #3

If you wish to use jquery, type $(“….”).is (“:focus”).

Take a peek at this stack to see what I’m talking about.

Answered by Michael

Solution #4

Because this is a block element, you must apply the tabindex property to it in order for it to acquire focus, like in

<div id="myID" tabindex="1"></div>

This element will be able to receive focus thanks to Tabindex. To prevent this behavior, use tabindex=”-1″ (or simply remove the attribute entirely).

Then all you have to do is relax.

if ($("#myID").is(":focus")) {...}

Or use the

$(document.activeElement)

As was originally said.

Answered by Eihwaz

Solution #5

Add the following code to your script, as well as the jQuery library.

var getElement = document.getElementById('myID');

if (document.activeElement === getElement) {
        $(document).keydown(function(event) {
            if (event.which === 40) {
                console.log('keydown pressed')
            }
        });
    }

Thank you…

Answered by Narendra1414

Post is based on https://stackoverflow.com/questions/36430561/how-can-i-check-if-my-element-id-has-focus