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?
This question is related to
javascript
jquery
html
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...
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.
Use document.activeElement
Should work.
P.S getElementById("myID")
not getElementById("#myID")
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
).
Source: Stackoverflow.com