How can I check if my Element ID has focus?

JavascriptJqueryHtml

Javascript Problem Overview


Let's say I have the following div that gets focus after a certain condition is met:

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

I want to create 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')
                }
            });
        }

I'm getting an error message in the console that says:

TypeError: Cannot read property 'hasFocus' of null

Any idea what I'm doing wrong here? Maybe the way I'm passing the div Id?

Javascript Solutions


Solution 1 - Javascript

Compare document.activeElement with the element you want to check for focus. If they are the same, the element is focused; otherwise, it isn't.

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

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

hasFocus is part of the document; there's no such method for DOM elements.

Also, document.getElementById doesn't use a # at the beginning of myID. Change this:

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

to this:

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

If you'd like to use a CSS query instead you can use querySelector (and querySelectorAll).

Solution 2 - Javascript

Use document.activeElement

Should work.

P.S getElementById("myID") not getElementById("#myID")

Solution 3 - Javascript

If you want to use jquery $("..").is(":focus").

You can take a look at this stack

Solution 4 - Javascript

This is a block element, in order for it to be able to receive focus, you need to add tabindex attribute to it, as in

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

Tabindex will allow this element to receive focus. Use tabindex="-1" (or indeed, just get rid of the attribute alltogether) to disallow this behaviour.

And then you can simply

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

Or use the

$(document.activeElement)

As been suggested previously.

Solution 5 - Javascript

Write below code in script and also add 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...

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
QuestionKode_12View Question on Stackoverflow
Solution 1 - JavascriptFlorrieView Answer on Stackoverflow
Solution 2 - JavascriptOen44View Answer on Stackoverflow
Solution 3 - JavascriptMichaelView Answer on Stackoverflow
Solution 4 - JavascriptEihwazView Answer on Stackoverflow
Solution 5 - JavascriptNarendra1414View Answer on Stackoverflow