views:

72

answers:

2

I have right now this code:

<ul><li class="listitem">text<li></ul>

jQuery:

$('.listitem').click(function() {  
  $("#elname").text($(this).text());  
  $('#slists').css('visibility','hidden')  
  $('#elname').css('visibility','visible')  
  $('#elname').css('display','inline-block')  
});

This is supposed to hide a div and it does, but when I append items to the ul (with the class listitem) nothing happens with the appended item, the class it gets is correct, the title, and the value too.

Can this have something to do with the code above being in the document ready function to do?

+7  A: 

Click events are set once on all elements in the DOM at the time of setting. Adding a list item won't regenerate these click items.

You'll need to use jQuery's live event functionality to create click events that apply to elements created on-the-fly.

ceejayoz
Thanks! So I understood it partially correct :)! very nice explanation to, and link!
Noor
+11  A: 

Use .live() instead, like this:

$('.listitem').live('click', function() {  
  $("#elname").text($(this).text())
              .css({ visibility:'visible', display: 'inline-block' });
  $('#slists').css('visibility','hidden')  
});

.live() listens at the document level for your click to bubble up...and new and old elements bubble this event the same way, so it doesn't care what was added later, where as your .click() handler binds a click to elements that existed at the time the selector was run.

Alternatively, you can give your <ul> an ID or class and use .delegate() like this:

$('#myUL').delegate('.listitem', 'click', function() {  
  $("#elname").text($(this).text())
              .css({ visibility:'visible', display: 'inline-block' });
  $('#slists').css('visibility','hidden')  
});

This results in less bubbling, so just a bit neater on the event side, it captures it at the <ul> instead of all the way up on document.

Nick Craver
thanks for the detailed explanation! and the better coding :) !!
Noor
@Noor - Welcome :) One other tip, unless you need those hidden elements to take up space while hidden, you can use `display` instead of `visibility` and simply call the `.show()` and `.hide()` shortcuts instead.
Nick Craver