Alan
Alan

Reputation: 46813

jquery set focus on dynamic content?

In jquery I've appended a <li> element to an unordered list.

How do I focus on the newly created <li> ?

If I do the following:

$("ul").append('<li><input type="text" value="Hi!"></li>');
$("li:last").focus(); //doesn't work because new <li> isn't in dom yet

the focus doesn't work, as noted above.

I know jquery 1.4.2 has a live() event handler which allows you load event handlers to dynamically added elements, but I'm not sure what I'm doing wrong:

$(document).ready(function () {

    $('li').live('load', function () {
       alert("hi!");
       $("li:last").focus();
    });
 });

Upvotes: 8

Views: 12326

Answers (3)

Uncle Dan
Uncle Dan

Reputation: 3290

This is an old post I know, but a simple way to solve this issue is to create a text input in your HTML and set its CSS to "display: none;". On the LI's click event, set the focus in this input and listen to its keypress events.

I've done it and it works like a charm.

Upvotes: 0

Nagaraja S
Nagaraja S

Reputation: 66

You can try this, $(YourElement).trigger("focus").

Upvotes: 1

Quentin
Quentin

Reputation: 943214

You can only set the focus to elements which can hold the focus. By default a list item cannot. This is why your first example fails, not because it isn't in the DOM (it is in the DOM, that is what append does)

In general you should use elements designed to hold the focus (i.e. set the focus on the input not the list item). You can also (but this is less backwards compatible and less logical) use HTML5's tabindex (probably setting it to 0).

onload will not work because list items do not load external content.

Upvotes: 7

Related Questions