1

I have built a <ul> list and it is being populated with <li id="subsitem"> from a jQuery function. I am trying to build a click function so that whenever one of those <li>'s is clicked, it disappears. I'm using the slideUp() function.

Here is my code:

$("#subsitem").click(function() {
  // Act on the event
  $(this).slideUp();
}); 

This doesn't work, yet when i change it to

$("li").click(function() {
  // Act on the event
  $(this).slideUp();
}); 

It works, but the only problem then is it works on all my <li>s. Anyone any tips?


update

Here is the code that is being used inside an .each()

$("#subs").append("<li><a href='#' class='subsitem'><div class='favicon'><img src='icon.png' width='16' height='16'></div>title</a></li>");
3
  • 1
    Please show some HTML, and the jQuery code that does the populating. Commented Aug 17, 2010 at 2:03
  • +1 @Ken. We cant help if we cant see the HTML Commented Aug 17, 2010 at 2:12
  • You shouldn't place a <div> inside an <a>. As inline elements, <a> tags should only contain other inline elements. Commented Aug 17, 2010 at 2:30

3 Answers 3

4

The problem is the first one is identifying by ID, which should be unique. You can change it to a class, and add the class to each li, to make it work.

$(".subitem").click(function() {
    // Act on the event
    $(this).slideUp();
}); 
Sign up to request clarification or add additional context in comments.

2 Comments

i know the code works, because if i create another list on the same page with the li and class, then the code works fine, its almost like my first ul list is bugged
You need to append $("#subs").append("<li class='subitem'><a href='#' class='subsitem'><div class='favicon'><img src='icon.png' width='16' height='16'></div>title</a></li>"); for my code to work. The difference being the <li> having subitem as the class.
2

Ok having used the jquery irc channel i managed to get the answer i was looking for.

I needed to use the .live() function. This is what my code now looks like

$("#subsitem").live('click',function(){
$(this).parent().slideUp();});

2 Comments

Upon investigation, that is exactly what you needed to do :) Thanks for the update, can you accept your own answer?
Yea I will do, once it allows me
1

What about doing something like:

$("#subsitem").click(function(){
    $(this).parent().slideUp();
});

To bind it to the parent <li> of the <a> that is clicked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.