Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    });
 });
like image 209
Alan Avatar asked May 17 '10 09:05

Alan


2 Answers

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.

like image 51
Quentin Avatar answered Oct 02 '22 23:10

Quentin


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

like image 44
Nagaraja S Avatar answered Oct 03 '22 00:10

Nagaraja S