196

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?

Kode_12
  • 4,506
  • 11
  • 47
  • 97
  • 5
    see thread http://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus – Brij Apr 05 '16 at 15:33
  • 7
    Not sure why this was marked as a duplicate (the other topic asks an entirely different question), but today we can use the `matches()` method. `var el = document.getElementById('myElement'); el.matches(':focus'); // If it has focus, it will return true.` – truefusion Sep 27 '19 at 13:03

5 Answers5

309

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).

Nebula
  • 6,614
  • 4
  • 20
  • 40
  • Why not just `document.activeElement.id=='myID'`? – Meisner Jul 21 '21 at 13:28
  • 1
    @Meisner `document.activeElement` might be `null`. – doesntgolf May 10 '22 at 15:19
  • Native JS `inputEl.addEventListener('wheel', (e) => {if (e.target === document.activeElement) {e.preventDefault()}})}`. For react, don't use `onWheel` because it's passive. Use a ref and apply to `inputRef.current` in `componentDidMount` – Josh Hibschman Jul 15 '22 at 14:59
  • 1
    Note that this may fail if the element is within an `iframe`, because `document.activeElement` will be the iframe, not the focused element inside it - see [Find focused element in document with many iframes](https://stackoverflow.com/questions/25420219/find-focused-element-in-document-with-many-iframes) – user56reinstatemonica8 Aug 08 '22 at 10:24
  • 1
    `dummyEl.contains(document.activeElement)` will tell you whether `dummyEl` or any of its children have the focus. – daniel p Dec 07 '22 at 09:22
28

Use document.activeElement

Should work.

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

Oen44
  • 3,156
  • 1
  • 22
  • 31
19

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

You can take a look at this stack

Community
  • 1
  • 1
Michael
  • 1,063
  • 14
  • 32
11

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.

Eihwaz
  • 1,234
  • 10
  • 14
  • Also point out the typo in `getElementById`. – Sinan Ünür Apr 05 '16 at 15:32
  • Thank you. I had already assigned a tabindex of -1. The $(document.activeElement) method works, but it's not specific to the div that I'm checking for focus ('myID'). It triggers the if statement when ANY div has focus, not just the one I'm concerned with ('myID') – Kode_12 Apr 05 '16 at 16:31
  • The jQuery method doesn't work at all – Kode_12 Apr 05 '16 at 16:32
  • @KunalOjha yes, it should fire whenever there's an active element, it's your job to check if it's the one you need. So, you'd do if ($(document.activeElement).is('#myID')) {...} Also, when you set tabindex to -1, it `disables` the focus event on that particular element, you need to set it to 1 or any other number. – Eihwaz Apr 05 '16 at 16:51
  • Still doesn't work :/ – Kode_12 Apr 05 '16 at 18:00
  • You should almost never be using positive numbers with `tabindex`. It should either be `0` or `-1`. See here: https://developers.google.com/web/fundamentals/accessibility/focus/using-tabindex – Stephen M Irving Jan 29 '20 at 21:03
-5

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...

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459