ms_nitrogen ms_nitrogen - 3 months ago 20
jQuery Question

.is(focus) vs .activeElement?

I've run into a strange problem, which I've already resolved using

document.activeElement.id
, but when using
$('#id').is(':focus')
seems to always return
false
.

In my console, I tested out the following...

> document.activeElement
<input type="text" for="zoomSlider" id="zoomText" oninput="zoomSliderUpdate(value)" value="100">

> $('#zoomText')
<input type="text" for="zoomSlider" id="zoomText" oninput="zoomSliderUpdate(value)" value="100">

> $('#zoomText').is(':focus')
false

> document.activeElement // to check if focus was lost somehow
<input type="text" for="zoomSlider" id="zoomText" oninput="zoomSliderUpdate(value)" value="100">


Why does
is(':focus')
return a false?

Answer

First, you have a bug in your code. It should be $('#zoomText').is(':focus').

Second, the element will only be in focus if the cursor is inside it. If your cursor is in the JavaScript console, then it has focus and causes the input to be blurred (out of focus).

Try this in the JavaScript console, and then quickly put your cursor back in the input. After 3 seconds, it will show "true" or "false" in the console to indicate the focus state of the "zoomText" element.

setTimeout(function() { console.log(jQuery('#zoomText').is(':focus')); }, 3000)

Comments