Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if my Element ID has focus? [duplicate]

People also ask

How do you know if an element has focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you check if a window is focused?

Use the document. hasFocus() method to check if a window has focus, e.g. if (document. hasFocus()) {} . The method returns a boolean value indicating whether the document or any element in the document has focus.

How do you know if an element is focused angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.


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


Use document.activeElement

Should work.

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


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

You can take a look at this stack


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.