Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the last focused element

I'm looking to determine which element had the last focus in a series of inputs, that are added dynamically by the user. This code can only get the inputs that are available on page load:

$('input.item').focus(function(){
    $(this).siblings('ul').slideDown();
});

And this code sees all elements that have ever had focus:

$('input.item').live('focus', function(){
    $(this).siblings('ul').slideDown();
});

The HTML structure is this:

<ul>
    <li><input class="item" name="goals[]">
    <ul>
        <li>long list here</li>
        <li>long list here</li>
        <li>long list here</li>
    </ul></li>
</ul>
<a href="#" id="add">Add another</a>

On page load, a single input loads. Then with each add another, a new copy of the top unordered list's contents are made and appended, and the new input gets focus. When each gets focus, I'd like to show the list beneath it. But I don't seem to be able to "watch for the most recently focused element, which exists now or in the future."

To clarify: I'm not looking for the last occurrence of an element in the DOM tree. I'm looking to find the element that currently has focus, even if said element is not present upon original page load.

this image http://droplr.com/174l8H+

So in the above image, if I were to focus on the second element, the list of words should appear under the second element. My focus is currently on the last element, so the words are displayed there.

Do I have some sort of fundamental assumption wrong?

like image 523
Joshua Cody Avatar asked Jun 02 '10 00:06

Joshua Cody


People also ask

How do you find the focus element?

It can be used to get the currently focused element in the document: Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

What is a focused element?

The focused element is the element that will receive keyboard and similar events by default.

How do you find the current focused element in react?

To check if an element is focused in React:Set the ref prop on the element. After the element is rendered, check if the element is the active element in the document. If it is, the element is focused.

How do you know if input is focused?

To detect if an element has focus, you compare it with the document. activeElement .


2 Answers

According to the documentation (see 'caveats'), .live() in jQuery 1.4.1 supports focus, mapping to focusin. I'd suggest creating an element in common scope to hold the last focused element. Perhaps like so:

var lastFocused;
$('input.item').live('focusin', function(){
    lastFocused = $(this);
});
like image 43
James Kolpack Avatar answered Sep 20 '22 18:09

James Kolpack


document.activeElement is what you want. It's part of HTML5 and supported by all modern browsers, including IE.

like image 129
Eli Grey Avatar answered Sep 21 '22 18:09

Eli Grey