Jquery "$("*:focus")" está vacío. ¿Cómo detectar dónde está el foco?

Im working with jQuery. There are input fields with ID's and attached .blur() events. The problem comes when I try to figure out the very new item where the focus is on:

 console.log ($(this).attr('id')+' -> '+$("*:focus").attr('id'));

pero esto $("*:focus").attr('id') is undefined. How to detect where is the focus?

preguntado el 31 de julio de 12 a las 15:07

Trata $(":focus").attr('id'), $(':focus') will select all focus element. You don't need * -

what if you simply try to print console.log($(":focus")) ? -

Keep in mind that on a large DOM a selector like this will be very slow, so try not to do it too often. -

ok this: console.log ($(this).attr('id')+' -> '+$(":focus").attr('id')); is still undefined -

Are you adding the new input dinamically? -

2 Respuestas

It would seem the blur/focus events are fired before a new element actually gets the :focus pseudo-class attached to it. Which is pretty interesting. Proof of what I mean in this violín

So that begs the question - why are you trying to do this? :)

My solución to your problem (if you absolutely need it like that) is to do it like so : VIOLÍN

Respondido 24 ago 13, 07:08

The problem you've got is that you try to get the item which has got focus but you do it to early. So what you do is this:

blur event gets fired
you try to get the element which has got focus
new element gets focus

Sure the easiest thing would be to add event listener for focus but if you don't want to do that this would be the trick:

$("input").blur(function() {
    setTimeout(function() {
    }, 1);

Demo en vivo


So actually the best solution would be the following because if you set a timeout it always depends on perfomance:

var sTempId;
    .focus(function() {
        if (sTempId)
            console.log ( sTempId + " -> " + $(this).attr("id") );
        sTempId = $(this).attr("id");

Demo en vivo

Respondido 31 Jul 12, 15:07

Eso hará $(this).attr('id') return undefined though. - Anders Arpi

If you use your technique with the code he actually wants to use, you will get "undefined -> focusedid" instead of "lastfocusid -> undefined". - Anders Arpi

no he can still save the id in a temp var before and use it after instead. - Noob

yea, I was thinking this way... I try to get the focused item at the very wrong tine - John Smith

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.