I have some issues with understanding jQuery on.
If i have a UL which has some dynamic Li elements created via jquery, which will set the first li to have the class selected – e.g.
<li class='selected'>text</li>
EDIT UDPATE:
Ok..so what i have is a set of dynamically generated LI from a REST call which is dynamically generated from a text box. What i need to happen is to essentially after i type in (keyup) i will get some results displayed (similar to autocomplete). What i then need to do is from within the context of the search box detect the up and down arrows and move the “.selected” class up and down the tree. The code below works for static lists, just not dynamically created ones.
some example code:
$('.txtSearchBox')
.unbind('keypress keyup')
.bind('keypress keyup', function (e) {
if ($(this).val().length < 3 && e.keyCode != 13) {
$('.searchWrapper').hide();
} else {
$('.searchWrapper').show();
SearchAutoComplete.init($('.searchWrapper'));
SearchAutoComplete.load();
}
if (e.keyCode == 38) { // up
var selected = $(".selected");
$(".searchWrapper li").removeClass("selected");
if (selected.prev().length == 0) {
selected.parent().children().last().addClass("selected");
} else {
selected.prev().addClass("selected");
}
}
if (e.keyCode == 40) { // down
var selected = $(".selected");
$(".searchWrapper li").removeClass("selected");
if (selected.next().length == 0) {
selected.parent().children().first().addClass("selected");
} else {
selected.next().addClass("selected");
}
}
});
$(".searchWrapper li").live('mouseover', function (e) {
$(".searchWrapper li").removeClass("selected");
$(this).addClass("selected");
});
As you can see this code detects the up and down arrow keys. The problem is for dynamic elements this does nothing. Im just confused as the on event should be on the li not the a?
Thanks
Chris
Try this:
From the JQuery docs when you provide a selector to the
on()function (“li”) the event handler is delegated.